package com.jy.modules.cims.deal.service;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jodd.util.StringUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleBeanUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.api.IJieYueSend;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService;
import com.jy.modules.cims.component.common.service.TCMmCreditDetailService;
import com.jy.modules.cims.component.common.service.TCMmCreditPackageService;
import com.jy.modules.cims.component.common.service.TCMmLoanDetailService;
import com.jy.modules.cims.component.common.service.TCMmTransExceptionService;
import com.jy.modules.cims.component.contract.ICContract;
import com.jy.modules.cims.component.creditRight.CCreditRightImpl;
import com.jy.modules.cims.component.creditRight.ICCreditRight;
import com.jy.modules.cims.component.creditRight.plan.CreditPlanConstant;
import com.jy.modules.cims.component.deal.ICDeal;
import com.jy.modules.cims.component.sysAssist.BatchService;
import com.jy.modules.cims.creditright.service.CreditRightService;
import com.jy.modules.cims.creditright.service.SettleCreditService;
import com.jy.modules.cims.data.common.dao.TCMmCooperorgDealDao;
import com.jy.modules.cims.data.common.dao.TCMmCreditDealDetailDao;
import com.jy.modules.cims.data.common.dao.TCMmCreditDetailDao;
import com.jy.modules.cims.data.common.dao.TCMmLoanDetailDao;
import com.jy.modules.cims.data.common.dao.TCMmQuotaCreditDetailDao;
import com.jy.modules.cims.data.common.dao.TCMmQuotaLoanDetailDao;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCostPlanDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDealDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditPackageDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaLoanDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmTransExceptionDTO;
import com.jy.modules.cims.data.dao.CreditDealDetailDao;
import com.jy.modules.cims.data.dao.CreditDetailDao;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dao.DictDetailDao;
import com.jy.modules.cims.data.dao.LoanDao;
import com.jy.modules.cims.data.dao.QuotaDao;
import com.jy.modules.cims.data.dto.ConfirmParamDto;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditDetailQueryDto;
import com.jy.modules.cims.data.dto.CreditRightDto;
import com.jy.modules.cims.data.dto.CreditRightTotalDto;
import com.jy.modules.cims.data.dto.DealDetailQueryDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.DictDetailDto;
import com.jy.modules.cims.data.dto.LoanDetailDto;
import com.jy.modules.cims.data.dto.LoanDto;
import com.jy.modules.cims.data.dto.LoanSettleApplyIdDto;
import com.jy.modules.cims.data.dto.QuotaCreditRightDto;
import com.jy.modules.cims.data.dto.QuotaDetailUnlockParamDto;
import com.jy.modules.cims.data.dto.QuotaDto;
import com.jy.modules.cims.data.dto.QuotaLoanDto;
import com.jy.modules.cims.data.dto.credit.CreditApplyDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateResultDto;
import com.jy.modules.cims.data.dto.credit.RedeemParamDto;
import com.jy.modules.cims.data.dto.credit.RedeemResultDto;
import com.jy.modules.cims.data.dto.loan.LoanDealSettleDto;
import com.jy.modules.cims.data.dto.loan.LoanTransferCrossBillDateDto;
import com.jy.modules.cims.data.interact.api.request.RequestLoanRedemptionReceiveDTO;
import com.jy.modules.cims.data.interact.api.request.RequestLoanRedemptionReceiveLoanDTO;
import com.jy.modules.cims.data.interact.api.request.RequestNoiteFinishDTO;
import com.jy.modules.cims.data.interact.api.request.RequestNoiteFinishListDTO;
import com.jy.modules.cims.data.interact.core.loan.response.ResponseRedemptionCreditDTO;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.interact.InteractClassInvokeService;
import com.jy.modules.cims.loan.service.LoanRedeemService;
import com.jy.modules.platform.sysdict.impl.SysDictAPImpl;
import com.jy.modules.platform.sysdict.service.SysDictDetailService;
import com.jy.platform.api.org.SessionAPI;
import com.jy.platform.api.sysdict.SysDictDetailVo;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;

/**
 * 交易处理服务层
 */
@Service("com.jy.modules.cims.deal.service.DealService")
public class DealService {
	private static final Logger logger = LoggerFactory.getLogger(DealService.class);

	/**
	 * 交易处理服务层
	 */
	public DealService() {
	}

	/**
	 * 交易处理服务层
	 */
	@Autowired
	@Qualifier("com.jy.modules.cims.component.deal.CDealImpl")
	public ICDeal iCDeal;
	@Autowired
	private TCMmCreditDetailDao creditDetailDao;
	
	@Autowired
	public TCMmCreditDealDetailDao creditDealDetailDao;
	
	@Autowired
	private CreditDetailDao iCreditDetailDao;
	
	@Autowired
	private TCMmLoanDetailDao loanDetailDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.creditRight.CCreditRightImpl")
	private ICCreditRight creditRight;


	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService")
	private TCMmCreditDealDetailService creditDealDetailService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmLoanDetailService")
	private TCMmLoanDetailService loanDetailService;
	@Autowired
	public DealDao dealDao;
	@Autowired
	public QuotaDao quotaDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	private ICInteract iCInteract;
	/**
	 * 系统交互处理服务层
	 */
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.InteractClassInvokeService")
	private InteractClassInvokeService interactClassInvokeService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.BatchService")
	public BatchService batchService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
	private TCMmCooperorgDealService cooperorgDealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditPackageService")
	private TCMmCreditPackageService creditPackageService;
	
	
	
	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.CreditRightService")
	private CreditRightService creditRightService;
	
	@Autowired
	@Qualifier("jieYueSendService")
	private IJieYueSend jieYueSend;
	
	@Autowired
	private TCMmCooperorgDealDao tCMmCooperorgDealDao;
	 
	/**
     * 
     */
	public ICContract iCContract;

	@Autowired
	private LoanDao ldao;

	@Autowired
	private TCMmQuotaLoanDetailDao qldao;

	@Autowired
	private TCMmQuotaCreditDetailDao quotaCreditDetailDao;

	@Autowired
	private TCMmLoanDetailDao lddao;

	@Autowired
	private SysDictAPImpl sysDictAPI;
	
	@Autowired
	private SysDictDetailService sysDictDetailService;
	
	@Autowired
	private DictDetailDao dictDetailDao;
	
	@Autowired
    public TCMmCreditDetailDao tCMmCreditDetailDao;
	
    @Autowired
   	@Qualifier("com.jy.modules.cims.component.common.service.TCMmTransExceptionService")
   	private TCMmTransExceptionService tCMmTransExceptionService;
    
    @Autowired
   	@Qualifier("com.jy.modules.cims.loan.service.LoanRedeemService")
    private LoanRedeemService loanRedeemService;
  
	@Autowired
	public CreditDealDetailDao creditDealDetailDaos;
	
	@Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService")
    private TCMmCreditDealDetailService tCMmCreditDealDetailService;
    
	@Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
    private TCMmCreditDetailService tCMmCreditDetailService;
	
	@Autowired
    @Qualifier("com.jy.modules.cims.creditright.service.SettleCreditService")
	private SettleCreditService settleCreditService;
	
	@Autowired
	private SessionAPI sessionAPI;
	
	/**
	 * 交易流水查询列表
	 * 
	 * @param dto
	 * @return
	 */
	public List<DealDto> getDealList(Map<String, Object> searchParams) {
		try {
			return dealDao.getDealListByPaging(searchParams);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 查询单个交易流水
	 * 
	 * @param dto
	 * @return
	 */
	public DealDto getDealStream(Map<String, Object> searchParams) {
		try {
			return dealDao.getDealStream(searchParams);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 交易流水查询列表
	 * 
	 * @param dto
	 * @return
	 */
	public List<DealDto> getSettleResultList(Map<String, Object> searchParams) {
		try {
			return dealDao.getSettleResultList(searchParams);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 交易流水查询列表
	 * 
	 * @param dto
	 * @return
	 */
	public List<DealDto> getDealListByIds(Map<String, Object> searchParams) {
		try {
			return dealDao.getDealListByIds(searchParams);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	

	/**
	 * 为支持不同类型的交易明细，返回值为object,客户端调用的时候，自己负责来转换特定类型
	 * 
	 * @param dto
	 * @return
	 */
	public List<CreditDetailDto> getDealDetailByCreditList(Map<String, Object> searchParams) {
		return dealDao.getDealDetailByCreditListByPaging(searchParams);
	}
	/**
	 * 分页查询受让债权可赎回列表
	 * @Title getDealCreditDetailByPackage
	 * @Description TODO
	 * @param searchParams
	 * @return 
	 * List<CreditDetailDto> 
	 * @author lizhiqiang
	 * @date 2016-2-22-下午3:35:31
	 * @update 
	 * @throws
	 */
	public List<CreditDetailDto> getDealCreditDetailByPackage(Map<String, Object> searchParams) {
		List<CreditDetailDto> creditList = dealDao.getTransfereeRedeemDetailByPaging(searchParams);
		if(creditList!=null && creditList.size()>0){
			DealDto dealdto = (DealDto) searchParams.get("dto");
			creditList = this.getCreditDetailRedemptionListByInterface(creditList, dealdto.getRedemptionDate());
		}
		return creditList;
	}
	/**
	 * 查询受让债权可赎回列表
	 * @Title getDealCreditDetailByPackage
	 * @Description TODO
	 * @param searchParams
	 * @return 
	 * List<CreditDetailDto> 
	 * @author lizhiqiang
	 * @date 2016-2-22-下午3:35:31
	 * @update 
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public List<CreditDetailDto> getDealCreditDetailByPackageAll(Map<String, Object> searchParams) {
		List<CreditDetailDto> result =  new ArrayList<CreditDetailDto>();
		List<CreditDetailDto> creditList = dealDao.getDealCreditDetailByPackage(searchParams);
		
		if(creditList!=null && creditList.size()>0){
			DealDto dealdto = (DealDto) searchParams.get("dto");
			Map<Object, Object> paramterMap = new HashMap<Object, Object>();
			paramterMap.put("redemptionDate", dealdto.getRedemptionDate());
			batchService.batchInvoke(DealService.class, "getRedemptionListByInterface", creditList, paramterMap, 100);
		
			result = (List<CreditDetailDto>)paramterMap.get("result");
			//creditList = this.getCreditDetailRedemptionListByInterface(creditList, dealdto.getRedemptionDate());
		}
		return result;
	}
	
	/**
	 * 受让赎回选择赎回债权，转换指定日期的债权价值
	 * 
	 * @param creditDetailList
	 * @param redeemDate
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CreditDetailDto> getRedemptionListByInterface(List<CreditDetailDto> creditDetailList,Map<Object, Object> paramterMap) {
		 List<CreditDetailDto> result = new ArrayList<CreditDetailDto>();
		 
		List<CreditDetailDto> list =  getCreditDetailRedemptionListByInterface(creditDetailList, (Date)paramterMap.get("redemptionDate"));
		
		
		if (null != paramterMap.get("result")){
			result = (List<CreditDetailDto>)paramterMap.get("result");
		}
		
		result = CollectionsUtils.union(result, list);
		
		//操作数据库或调用某方法返回的结果  
		paramterMap.put("result", result);
		
		return result;
		  
		//return this.getCreditDetailRedemptionListByInterface(creditDetailList, (Date)paramterMap.get("redemptionDate"));
		
	}
	
	/**
	 * 为支持不同类型的交易明细，返回值为object,客户端调用的时候，自己负责来转换特定类型
	 * 
	 * @param dto
	 * @return
	 */
	public String getDealDetailList(Map<String, Object> searchParams) {
		List<CreditDetailDto> list = dealDao.getDealDetailByCreditList(searchParams);
		String isNotExport = "true";
		
		for(CreditDetailDto creditDetailDto : list){
			String creditEachStatus = creditDetailDto.getCreditEachStatus();
			if(creditEachStatus!=null){
				if(creditEachStatus.equals(CimsConstant.LOAN_EACH_STATUS_URL)){
					isNotExport = "false";
					break;
				}
			}
		}
		return isNotExport;
	}
	
	/**
	 * 获取带有费用项的债权明细集合
	 * @param searchParams
	 * @return
	 */
	public List<CreditDetailDto>  getDealDetailListReturn(Map<String, Object> searchParams) throws Exception {
		List<CreditDetailDto> list = dealDao.getDealDetailListReturn(searchParams);
		
		return list;
	}
	
//	/**
//	 * 获取流水号下所有的债权信息
//	 * 
//	 * @Title getDealDetailByCreditListForExport
//	 * @Description TODO
//	 * @param searchParams
//	 * @return List<DealDetailByCreditDto>
//	 * @author zhoupeng
//	 * @date 2016-4-14-上午11:22:05
//	 * @update
//	 * @throws
//	 */
//	public List<CreditDetailDto>  getDealDetailListReturn(Map<String, Object> searchParams) throws Exception {
//		List<CreditDetailDto> list = dealDao.getDealDetailByCreditList(searchParams);
//		
//		return list;
//	}

	/**
	 * 提供债权导出的数据源
	 * 
	 * @Title getDealDetailByCreditListForExport
	 * @Description TODO
	 * @param searchParams
	 * @return List<DealDetailByCreditDto>
	 * @author lizhiqiang
	 * @date 2015-2-4-上午11:22:05
	 * @update
	 * @throws
	 */
	public List<CreditDetailDto> getDealDetailByCreditListForExport(Map<String, Object> searchParams) {

		
		List<CreditDetailDto> list = dealDao.getDealDetailByCreditList(searchParams);
		List<CreditDetailDto> creditDetaillist = new ArrayList<CreditDetailDto>();
		Map<String , Map<String,String>> dictMap = new HashMap<String , Map<String,String>>();
		dictMap.put("SEX", getDictDetailName("SEX"));
		dictMap.put("IDTYPE", getDictDetailName("IDTYPE"));
		dictMap.put("EDUCATION", getDictDetailName("EDUCATION"));
		dictMap.put("HOUSETYPE", getDictDetailName("HOUSETYPE"));
		dictMap.put("MARITALSTATUS", getDictDetailName("MARITALSTATUS"));
		dictMap.put("CHILDSTATUS", getDictDetailName("CHILDSTATUS"));
		dictMap.put("JOBNATURE", getDictDetailName("JOBNATURE"));
		dictMap.put("LOANPURPOSE", getDictDetailName("LOANPURPOSE"));
		dictMap.put("HOUSETYPE", getDictDetailName("HOUSETYPE"));
		dictMap.put("DUTY", getDictDetailName("DUTY"));
		dictMap.put("CM_REPAYMENTWAY", getDictDetailName("CM_REPAYMENTWAY"));
		dictMap.put("CENSUSTYPE", getDictDetailName("CENSUSTYPE"));
		dictMap.put("creditorStatus", getDictDetailName("creditorStatus"));
		dictMap.put("BANKCODE", getDictDetailName("BANKCODE"));
		
		
		try {
			for (CreditDetailDto creditDetailDto : list) {
				creditDetailDto.setSex(dictMap.get("SEX").get(creditDetailDto.getSex()));// 性别
				creditDetailDto.setCardType(dictMap.get("IDTYPE").get( creditDetailDto.getCardType()));// 证件类型
				creditDetailDto.setDiploma(dictMap.get("EDUCATION").get( creditDetailDto.getDiploma()));// 学历
				creditDetailDto.setIsHasHouse(dictMap.get("HOUSETYPE").get( creditDetailDto.getIsHasHouse()));
				creditDetailDto.setMarryStatus(dictMap.get("MARITALSTATUS").get( creditDetailDto.getMarryStatus()));
				creditDetailDto.setIsHasChild(dictMap.get("CHILDSTATUS").get( creditDetailDto.getIsHasChild()));
				if(CimsConstant.COOPERORG_CODE_TBJ.equals(creditDetailDto.getCooperorgCode())){
					creditDetailDto.setCompanyType(tbjGetDictDetailName("cims_jType", creditDetailDto.getCompanyType()));
					creditDetailDto.setBorrowerUse(tbjGetDictDetailName("cims_loanPurpose", creditDetailDto.getBorrowerUse()));
					creditDetailDto.setHomeType(tbjGetDictDetailName("cims_homeType", creditDetailDto.getHomeType()));
					creditDetailDto.setDuty(tbjGetDictDetailName("cims_jPosition", creditDetailDto.getDuty()));
				}else{
					creditDetailDto.setCompanyType(dictMap.get("JOBNATURE").get(creditDetailDto.getCompanyType()));
					creditDetailDto.setBorrowerUse(dictMap.get("LOANPURPOSE").get(creditDetailDto.getBorrowerUse()));
					creditDetailDto.setHomeType(dictMap.get("HOUSETYPE").get( creditDetailDto.getHomeType()));
					creditDetailDto.setDuty(dictMap.get("DUTY").get( creditDetailDto.getDuty()));
				}
				creditDetailDto.setRepayType(dictMap.get("CM_REPAYMENTWAY").get(creditDetailDto.getRepayType()));
				creditDetailDto.setHouseholdType(dictMap.get("CENSUSTYPE").get(creditDetailDto.getHouseholdType()));
				creditDetailDto.setCreditorStatus(dictMap.get("creditorStatus").get(creditDetailDto.getCreditorStatus()));
				creditDetailDto.setRepayBankCode(dictMap.get("BANKCODE").get( creditDetailDto.getRepayBankCode()));
//				creditDetailDto.setDealCreditorStatus(getDictDetailName("creditorStatus", creditDetailDto.getDealCreditorStatus()));
				
				BigDecimal yh = null;
				if(creditDetailDto.getTotalRepaymentValue()!=null
						&&creditDetailDto.getTotalRepaymentValue().compareTo(new BigDecimal(0))>0){
					yh = creditDetailDto.getThisRepaySum()
							.divide(creditDetailDto.getTotalRepaymentValue(),2,BigDecimal.ROUND_HALF_DOWN)
							.multiply(new BigDecimal(100));
				}
				if(yh!=null){
					yh = yh.setScale(2,   BigDecimal.ROUND_HALF_UP);
					creditDetailDto.setYueHuanZb(yh.toString()+"%");
				}
				creditDetaillist.add(creditDetailDto);
			}
			
			//2016-10-26 add 
			List<TCMmCostPlanDTO> costPlanList = null;
			Object obj = searchParams.get("dto");
			if (null != obj) {
				if (obj instanceof CreditDetailQueryDto) {
					try {
						CreditDetailQueryDto dto = (CreditDetailQueryDto) obj;
						costPlanList = settleCreditService.searchCostPlanByDealCode(dto.getDealCode());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			
			if (CollectionsUtils.isEmpty(costPlanList)) {
				return creditDetaillist;
			} else {
				return settleCreditService.tranCreditDetailList(creditDetaillist, costPlanList);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return creditDetaillist;
	}

	/**
	 * 查询已经选择债权价值的
	 * 
	 * @Title getDealDetailByCreditListByTotal
	 * @Description TODO
	 * @param paramMap
	 * @return CreditRightDto
	 * @author lizhiqiang
	 * @date 2015-2-3-下午3:18:29
	 * @update
	 * @throws
	 */
	public CreditRightDto getDealDetailByCreditListByTotal(Map<String, Object> paramMap) {
		return dealDao.getDealDetailByCreditListByTotal(paramMap);
	}

	/**
	 * 统计查询每天合作机构的转让债权价值、赎回债权价值、匹配债权价值
	 * 
	 * @Title getDealDetailByCreditListByTotal
	 * @Description TODO
	 * @param paramMap
	 * @return CreditRightDto
	 * @author lizhiqiang
	 * @date 2015-4-14-下午9:00:19
	 * @update
	 * @throws
	 */
	public List<CreditRightTotalDto> getDealCreditDetailTotalByDay(Map<String, Object> paramMap) {
		return dealDao.getDealCreditDetailTotalByDayByPaging(paramMap);
	}

	/**
	 * 查询已经选择贷款价值的
	 * 
	 * @Title getDealDetailByCreditListByTotal
	 * @Description TODO
	 * @param paramMap
	 * @return CreditRightDto
	 * @author lizhiqiang
	 * @date 2015-2-3-下午3:18:29
	 * @update
	 * @throws
	 */
	public LoanDto getDealDetailByLoanListByTotal(Map<String, Object> paramMap) {
		return dealDao.getDealDetailByLoanListByTotal(paramMap);
	}

	/**
	 * 根据ID返回交易明细信息
	 * 
	 * @param dto
	 * @return
	 */
	public Object getDealDetailByID(DealDetailQueryDto dto) {
		// TODO implement here
		return null;
	}

	/**
	 * 删除交易信息，交易在途或者已完成不允许删除，先删除明细，再删除交易，如果明细对应的额度申请编号已经完成，则需要调用释放接口
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 *             String
	 * @author lizhiqiang
	 * @date 2015-1-29-下午4:49:42
	 * @update
	 * @throws
	 */
	public DataMsg confirmDoDeleteDeal(String ids,DataMsg dataMsg) throws Exception {
		StringBuffer resultstr = new StringBuffer("交易流水号（");
		String[] id = ids.split(",");
		int count = 0;
		for (int i = 0; i < id.length; i++) {
			TCMmCooperorgDealDTO cooperorgDealDTO = cooperorgDealService.queryTCMmCooperorgDealByPrimaryKey(id[i]);
			if (CimsConstant.DEAL_STATUS_CREATE.equals(cooperorgDealDTO.getCooperativeAgencyDealStatus())
					|| SimpleStringUtils.isEmpty(cooperorgDealDTO.getCooperativeAgencyDealStatus())) {
				// 删除明细
				if (CimsConstant.DEAL_TYPE_CREDIT_OUT.equals(cooperorgDealDTO.getDealType())) {
					Map<String, Object> searchParams = new HashMap<String, Object>();
					TCMmCreditDealDetailDTO creditDealDetailDTO = new TCMmCreditDealDetailDTO();
					creditDealDetailDTO.setDealStreamCode(cooperorgDealDTO.getDealCode());
					creditDealDetailDTO.setValidateState("1");
					searchParams.put("dto", creditDealDetailDTO);
					List<TCMmCreditDealDetailDTO> creditDealDetailList = creditDealDetailService.searchTCMmCreditDealDetail(searchParams);
					if (creditDealDetailList.size() > 0) {
						StringBuffer transferIds = new StringBuffer();
						for (TCMmCreditDealDetailDTO tcMmCreditDealDetailDTO : creditDealDetailList) {
							transferIds.append("," + tcMmCreditDealDetailDTO.getTransferId());
						}
						count++;
						this.confirmRemoveDetailByCredit(new BaseDTO(), transferIds.substring(1).toString(), cooperorgDealDTO.getDealCode());
					}
				} else if (CimsConstant.DEAL_TYPE_LOAN_OUT.equals(cooperorgDealDTO.getDealType())) {
					Map<String, Object> searchParams = new HashMap<String, Object>();
					TCMmLoanDetailDTO loanDetailDTO = new TCMmLoanDetailDTO();
					loanDetailDTO.setDealCode(cooperorgDealDTO.getDealCode());
					loanDetailDTO.setValidateState("1");
					searchParams.put("dto", loanDetailDTO);
					List<TCMmLoanDetailDTO> loanDetailList = loanDetailService.searchTCMmLoanDetail(searchParams);
					if (loanDetailList.size() > 0) {
						StringBuffer contractNos = new StringBuffer();
						StringBuffer loanids = new StringBuffer();
						for (TCMmLoanDetailDTO tcMmLoanDetailDTO : loanDetailList) {
							contractNos.append("," + tcMmLoanDetailDTO.getContractNo());
							loanids.append("," + tcMmLoanDetailDTO.getId());
						}
						this.doConfirmRemoveDetailByLoan(new BaseDTO(), contractNos.substring(1).toString(), loanids.substring(1).toString());
						count++;
					}
				}
				cooperorgDealService.deleteTCMmCooperorgDealByPrimaryKey(new BaseDTO(), id[i]);

			} else {
				resultstr.append(cooperorgDealDTO.getDealCode() + ",");
			}
		}
		if ("交易流水号（".equals(resultstr.toString())) {

			resultstr = new StringBuffer("");
			resultstr.append("删除成功");
			dataMsg.setMsg(resultstr.toString());
			dataMsg.setStatus("ok");
		} else {
			if (count > 0){
				resultstr.append("已经进入交易状态，不能删除，其余删除成功");
				dataMsg.setMsg(resultstr.toString());
				dataMsg.setStatus("ok");
			}else{
				resultstr.append("已经进入交易状态，不能删除");
				dataMsg.setMsg(resultstr.toString());
				dataMsg.setStatus("no");
			}
		}
		return dataMsg;
	}

	/**
	 * 删除债权交易明细信息
	 * 
	 * @param detailCode
	 */
	public void deleteDetailByCredit(BaseDTO baseDto, String transferIds, String dealCode) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", baseDto);
		paramMap.put("transferIds", transferIds);
		QuotaCreditRightDto quotaCreditRightDto = new QuotaCreditRightDto();
		quotaCreditRightDto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);
		quotaCreditRightDto.setTransferIds(transferIds);
		// 修改额度申请的状态
		// creditRight.updateTCMmQuotaCreditDetailStatusByTransferIds(quotaCreditRightDto);
		// 删除债权交易明细
		creditRight.deleteTCMmCreditDealDetailByTransferIds(baseDto, transferIds, dealCode);
		// 删除债权明细
		creditRight.deleteTCMmCreditDetailByTransferIds(baseDto, transferIds);
	}

	/**
	 * 删除债权交易明细入口
	 * 
	 * @Title confirmRemoveDetailByCredit
	 * @Description TODO
	 * @param baseDto
	 * @param transferIds
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-4-9-下午2:50:21
	 * @update
	 * @throws
	 */
	public void confirmRemoveDetailByCredit(BaseDTO baseDto, String transferIds, String dealCode) throws Exception {
		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		transferIds = transferIds.replaceAll(",", "','");
		// 删除本地明细
		this.doRegisterRemoveDetailByCredit(baseDto, transferIds, busiNoForInteract, dealCode);
		this.removeDetailByCredit(baseDto, transferIds, busiNoForInteract);
	}

	/**
	 * 删除债权交易明细 注册 调用接口
	 * 
	 * @Title doRegisterRemoveDetailByCredit
	 * @Description TODO
	 * @param baseDto
	 * @param transferIds
	 * @param busiNoForInteract
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-4-9-下午2:56:35
	 * @update
	 * @throws
	 */
	public void doRegisterRemoveDetailByCredit(BaseDTO baseDto, String transferIds, String busiNoForInteract, String dealCode) throws Exception {
		this.deleteDetailByCredit(baseDto, transferIds, dealCode);
		iInteractAssist.registerDealIrtService(busiNoForInteract);
		/* 保存执行上下文 */
		interactClassInvokeService
				.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "removeDetailByCredit", transferIds, busiNoForInteract);
	}

	/**
	 * 本地执行删除以后，如果额度申请流水已经失效，需要调用释放接口
	 * 
	 * @Title removeDetailByCredit
	 * @Description TODO
	 * @param baseDto
	 * @param transferIds
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-1-31-上午11:03:29
	 * @update
	 * @throws
	 */
	public void removeDetailByCredit(BaseDTO baseDto, String transferIds, String busiNoForInteract) throws Exception {
		// 调用释放债权接口
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("transferIds", transferIds);
		List<TCMmQuotaCreditDetailDTO> batchIdsList = quotaDao.getQuotaCreditRightDtoByTransferIds(paramMap);
		if (batchIdsList.size() > 0) {
			List<QuotaDetailUnlockParamDto.CreditRightUnlockInfo> creditRightUnlockInfoList = new ArrayList<QuotaDetailUnlockParamDto.CreditRightUnlockInfo>();
			for (TCMmQuotaCreditDetailDTO tcMmQuotaCreditDetailDTO : batchIdsList) {
				QuotaDetailUnlockParamDto.CreditRightUnlockInfo creditRightUnlockInfo = new QuotaDetailUnlockParamDto.CreditRightUnlockInfo();
				creditRightUnlockInfo.setCreditId(tcMmQuotaCreditDetailDTO.getCreditCode());// 债权编号
				creditRightUnlockInfo.setTransferId(tcMmQuotaCreditDetailDTO.getTransferId());// 转让编号
				creditRightUnlockInfo.setEachRepaymentValue(tcMmQuotaCreditDetailDTO.getThisRepaySum());// //本次释放对应月还金额(本期还款金额)
				creditRightUnlockInfo.setFreeValue(tcMmQuotaCreditDetailDTO.getThisMakeCreditorValue());// 本次释放债权价值（本次转让债权价值）
				creditRightUnlockInfo.setIsWhole(CimsConstant.CREDIT_ISWHOLE);// 全部释放
				creditRightUnlockInfoList.add(creditRightUnlockInfo);
			}
			QuotaDetailUnlockParamDto paramDto = new QuotaDetailUnlockParamDto();
			paramDto.setQuotaType(CimsConstant.QUOTATYPE_CR);
			paramDto.setCreditRightUnlockList(creditRightUnlockInfoList);
			paramDto.setDealCode(busiNoForInteract);
			// 调用释放债权的接口
			iCInteract.quotaDetailUnlock(paramDto);
		}
	}

	/**
	 * 删除贷款交易明细信息
	 * 
	 * @param detailCode
	 */
	public void deleteDetailByLoan(BaseDTO baseDto, String loanids) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", baseDto);
		paramMap.put("ids", loanids);
		// iCLoan.updateTCMmQuotaLoanDetailStatusByIntoAppCodes(quotaLoanDto);

		loanDetailDao.deleteTCMmLoanDetailByPrimaryKey(paramMap);
	}

	/**
	 * 删除贷款明细入口
	 * 
	 * @Title confirmRemoveDetailByLoan
	 * @Description TODO
	 * @param baseDto
	 * @param contractNos
	 * @param loanids
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-4-8-下午4:43:31
	 * @update
	 * @throws
	 */
	public void doConfirmRemoveDetailByLoan(BaseDTO baseDto, String contractNos, String loanids) throws Exception {
		/*String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		this.doRegisterRemoveDetailByLoan(baseDto, contractNos, loanids, busiNoForInteract);*/
		this.deleteDetailByLoan(baseDto, loanids);
		this.removeDetailByLoan(baseDto, contractNos, loanids);
	}

	/**
	 * 注册删除贷款明细
	 * 
	 * @Title doRegisterRemoveDetailByLoan
	 * @Description TODO
	 * @param baseDto
	 * @param contractNos
	 * @param loanids
	 * @param busiNoForInteract
	 * @throws Exception
	 * @author lizhiqiang
	 * @date 2015-4-8-下午4:43:50
	 * @update
	 * @throws
	 */
	public void doRegisterRemoveDetailByLoan(BaseDTO baseDto, String contractNos, String loanids, String busiNoForInteract) throws Exception {
		this.deleteDetailByLoan(baseDto, loanids);
		iInteractAssist.registerDealIrtService(busiNoForInteract);
		/* 保存执行上下文 */
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "removeDetailByLoan", baseDto, contractNos, loanids,
				busiNoForInteract);
	}

	/**
	 * 本地执行删除以后，需要调用释放接口
	 * 
	 * @Title removeDetailByCredit
	 * @Description TODO
	 * @param baseDto
	 * @param transferIds
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-1-31-上午11:03:29
	 * @update
	 * @throws
	 */
	public void removeDetailByLoan(BaseDTO baseDto, String contractNos, String loanids) throws Exception {
		// 调用释放债权接口
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("contractNos", contractNos.replace(",", "','"));
		
		List<TCMmQuotaLoanDetailDTO> quotaLoanDetailList = quotaDao.getQuotaLoanDtoByContractNos(paramMap);
		if (quotaLoanDetailList.size() > 0) {
			List<QuotaDetailUnlockParamDto.LoanUnlockInfo> loanUnlockInfoList = new ArrayList<QuotaDetailUnlockParamDto.LoanUnlockInfo>();
			for (TCMmQuotaLoanDetailDTO quotaLoanDetailDTO : quotaLoanDetailList) {
				QuotaDetailUnlockParamDto.LoanUnlockInfo loanUnlockInfo = new QuotaDetailUnlockParamDto.LoanUnlockInfo();
				loanUnlockInfo.setContractNo(quotaLoanDetailDTO.getContractNo());
				loanUnlockInfo.setUnlockReason("人工取消");
				loanUnlockInfo.setUnlockType(CimsConstant.LOAN_OPER_TYPE_LB); // 取消额度申请/日终释放额度/人工驳回
				loanUnlockInfoList.add(loanUnlockInfo);
			}
			QuotaDetailUnlockParamDto paramDto = new QuotaDetailUnlockParamDto();
			paramDto.setQuotaType(CimsConstant.QUOTATYPE_LOAN);
			paramDto.setUnlockList(loanUnlockInfoList);
			// 调用释放贷款的接口
			iCInteract.quotaDetailUnlock(paramDto);
		}
	}

	/**
	 * 交易导入处理
	 * 
	 * @param dealCode
	 * @return
	 */
	public void doExcelImport(List<CreditDetailDto> creditDealList) throws Exception {
		for (CreditDetailDto creditDetailDto : creditDealList) {
			if (SimpleStringUtils.isEmpty(creditDetailDto.getTransferId())) {
				continue;
			}
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCreditDetailDTO creditDetailDTO = new TCMmCreditDetailDTO();
			creditDetailDTO.setTransferId(creditDetailDto.getTransferId());
			searchParams.put("dto", creditDetailDTO);
			creditDetailDTO = creditDetailDao.searchTCMmCreditDetail(searchParams).get(0);
			creditDetailDTO.setTransferId(creditDetailDto.getTransferId());// 转让编号
			creditDetailDTO.setCreditorStatus(creditDetailDto.getDealCreditorStatus());// 回复状态
			creditDetailDTO.setMakeCreditorValue(creditDetailDto.getMakeCreditorValue());// 回复债权价值
			creditDetailDTO.setDeliverDate(creditDetailDto.getDeliverDate());// 交割日期
			creditDetailDTO.setPlanRedeemDate(creditDetailDto.getPlanRedeemDate());//计划赎回日期
			searchParams.clear();
			searchParams.put("dto", creditDetailDTO);
			creditDetailDao.updateTCMmCreditDetail(searchParams);// 更新交易明细表

		}
	}

	/**
	 * 债权转让流水号
	 * 
	 * @param quotaCode
	 * @return
	 */
	public JResult doGetDealCode(StringBuffer dealCode) throws Exception {
		JResult result = new JResult();
		dealCode = dealCode.append(iCDeal.createDealCode(CimsConstant.BIZNO_TYPE_CRTO));
		result.setSuccess(true);
		if (SimpleStringUtils.isBlank(dealCode))
			result.setSuccess(false);
		return result;
	}
	/**
	 * 受让赎回流水号
	 * 
	 * @param quotaCode
	 * @return
	 */
	public JResult doGetTransferDealCode(StringBuffer dealCode) throws Exception {
		JResult result = new JResult();
		dealCode = dealCode.append(iCDeal.createDealCode(CimsConstant.BIZNO_TYPE_SRSH));
		result.setSuccess(true);
		if (SimpleStringUtils.isBlank(dealCode))
			result.setSuccess(false);
		return result;
	}

	/**
	 * 记录债权的挑选信息,先将债权的额度申请明细表的状态，然后插入到债权交易流水明细表、债权明细表
	 * 
	 * @throws Exception
	 */
	public String saveCreditDealDetail(QuotaCreditRightDto qcreditdto, TCMmCooperorgDealDTO dealdto) throws Exception {
		// 按明细处理
		if (CimsConstant.PAG_IS_FULL_N.equals(qcreditdto.getPagIsFull())) {
			qcreditdto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_LOCK);// 交易占用
			// 更新额度债权明细状态
			creditRight.updateTCMmQuotaCreditDetailStatus(qcreditdto);
			// 保存债权交易明细
			creditRight.saveCreditDealDetail(qcreditdto, dealdto);
			// 保存债权明细
			QuotaDetailUnlockParamDto paramDto = creditRight.saveCreditDetail(qcreditdto, dealdto);
			String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
			if (paramDto != null) {
				paramDto.setQuotaType(CimsConstant.QUOTATYPE_CR);
				paramDto.setDealCode(busiNoForInteract);
				doRegisterQuotaDetailUnlock(busiNoForInteract, paramDto);
				this.doQuotaDetailUnlock(paramDto);
			}
			return "添加成功！";
		} else {// 按包处理
			return this.saveCreditDealDetailByPag(qcreditdto, dealdto);
		}
	}

	/**
	 * 记录债权的挑选信息,先将债权的额度申请明细表的状态，然后插入到债权交易流水明细表、债权明细表 处理一个包
	 * 
	 * @Title saveCreditDealDetailByPag
	 * @Description TODO
	 * @param qcreditdto
	 * @param dealdto
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-4-18-上午11:10:18
	 * @update
	 * @throws
	 */
	public String saveCreditDealDetailByPag(QuotaCreditRightDto qcreditdto, TCMmCooperorgDealDTO dealdto) throws Exception {
		// 1、查询是否有此包的额度申请
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		TCMmQuotaDTO quotaDTO = new TCMmQuotaDTO();
		quotaDTO.setCreditPackageName(qcreditdto.getPackageNum());
		quotaDTO.setCooperorgCode(qcreditdto.getCooperorgCode());
		quotaDTO.setContractCode(qcreditdto.getContractCode());
		paramsMap.put("dto", quotaDTO);
		List<QuotaDto> quotaDTOList = quotaDao.searchQuota(paramsMap);
		if (quotaDTOList == null || quotaDTOList.size() == 0) {
			return "额度申请中不存在此包！";
		} else {

			QuotaDto quotaDto = quotaDTOList.get(0);
			TCMmQuotaCreditDetailDTO quotaCreditDetailDTO = new TCMmQuotaCreditDetailDTO();
			quotaCreditDetailDTO.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);//
			quotaCreditDetailDTO.setQuotaCode(quotaDto.getQuotaCode());
			paramsMap.clear();
			paramsMap.put("dto", quotaCreditDetailDTO);

			// 2、保存到债权交易明细
			List<TCMmQuotaCreditDetailDTO> quotaCreditDetailList = quotaCreditDetailDao.searchTCMmQuotaCreditDetail(paramsMap);
			if (quotaCreditDetailList == null || quotaCreditDetailList.size() == 0)
				return "额度申请中没有债权明细！";
			List<TCMmCreditDealDetailDTO> creditDealDetailList = new ArrayList<TCMmCreditDealDetailDTO>();
			List<TCMmCreditDetailDTO> creditDetailList = new ArrayList<TCMmCreditDetailDTO>();
			for (TCMmQuotaCreditDetailDTO quotaCreditDetail : quotaCreditDetailList) {
				TCMmCreditDealDetailDTO cdddto = new TCMmCreditDealDetailDTO();
				cdddto.setDealStreamCode(dealdto.getDealCode());// 交易编号
				cdddto.setCooperorgCode(dealdto.getCooperorgCode());// 合作机构编号
				cdddto.setAgreementCode(quotaCreditDetail.getArgeementCode());// 协议编号
				cdddto.setTransferId(quotaCreditDetail.getTransferId());// 转让编号
				cdddto.setDealSerial(1L);// 交易序号
				creditDealDetailList.add(cdddto);

				TCMmCreditDetailDTO cddto = new TCMmCreditDetailDTO();
				SimpleBeanUtils.copyBean2Bean(cddto, quotaCreditDetail);
				cddto.setId(null);
				cddto.setContractCode(dealdto.getContractCode());
				cddto.setCooperorgCode(dealdto.getCooperorgCode());
				cddto.setCreditSource(CimsConstant.CREDIT_SOURCE_CRE);// 债权来源:01-债权池
				cddto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WAY);// 债权状态:01-在途
				cddto.setCreditorValueUpdateDate(new Date()); //债权价值刷日期
				creditDetailList.add(cddto);
			}
			try {
				batchService.batchInvoke(CCreditRightImpl.class, "insertCreditDealDetailByBatch", creditDealDetailList, null, 500);
//				creditRight.insertCreditDealDetailByBatch(creditDealDetailList);

			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("批量插入债权交易明细失败！");
			}
			// 3、保存到债权明细
			try {
				batchService.batchInvoke(CCreditRightImpl.class, "insertCreditDetailByBatch", creditDetailList, null, 500);
//				creditRight.insertCreditDetailByBatch(creditDetailList);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("批量插入债权明细失败！");
			}
			// 4、更新此包下的所有申请债权明细为已占用
			try {
				quotaCreditDetailDTO.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_LOCK);// 交易占用
				paramsMap.clear();
				paramsMap.put("dto", quotaCreditDetailDTO);
				quotaDao.updateQuotaCreditDetailByQuotaCode(paramsMap);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("更新额度债权明细失败！");
			}
		}
		return "添加成功！";
	}

	/**
	 * 注册额度释放
	 * 
	 * @param busiNoForInteract
	 * @param paramDto
	 * @throws Exception
	 */
	public void doRegisterQuotaDetailUnlock(String busiNoForInteract, QuotaDetailUnlockParamDto paramDto) throws Exception {
		iInteractAssist.registerDealIrtService(busiNoForInteract);
		/* 保存执行上下文 */
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "doQuotaDetailUnlock", paramDto, busiNoForInteract);
	}

	public void doQuotaDetailUnlock(QuotaDetailUnlockParamDto paramDto) {
		// 调用释放债权的接口
		iCInteract.quotaDetailUnlock(paramDto);
	}

	/**
	 * @author zhiqiang
	 * @description: 指定字段更新对象T_C_MM_QUOTA_LOAN_DETAIL
	 * @date 2015-01-12 20:34:29
	 * @param paramMap
	 */
	public void updateTCMmQuotaLoanDetailStatus(QuotaLoanDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		ldao.updateTCMmQuotaLoanDetailStatusByContractNos(paramMap);
	}

	/**
	 * 根据额度编号更新贷款明细状态
	 * @author zhiqiang
	 * @description: 指定字段更新对象T_C_MM_QUOTA_LOAN_DETAIL
	 * @date 2015-01-12 20:34:29
	 * @param paramMap
	 */
	public void updateTCMmQuotaLoanDetailStatusByQuota(Map<String, Object> paramMap) throws Exception {
		ldao.updateTCMmQuotaLoanDetailStatusByQuotaCode(paramMap);
	}
	
	/**
	 * 记录贷款的挑选信息,按贷款的额度申请明细表的状态，然后插入到贷款信息表
	 */
	public void saveLoanDealDetail(QuotaLoanDto qloandto, TCMmCooperorgDealDTO dealdto) throws Exception {
		
		if (CimsConstant.PAG_IS_FULL_Y.equals(qloandto.getQuotaCodeIsAll())&&SimpleStringUtils.isNotEmpty(qloandto.getQuotaCode())) {
			this.saveLoanDealDetailByQuota(qloandto, dealdto);
		}else{
			qloandto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_LOCK);
			qloandto.setContractNos(qloandto.getContractNos().replace(",", "','"));
			this.updateTCMmQuotaLoanDetailStatus(qloandto);
	
			String[] ids = qloandto.getQldids().split(",");
			for (int i = 0; i < ids.length; i++) {
				TCMmQuotaLoanDetailDTO quotaLoanDetailDTO = qldao.findTCMmQuotaLoanDetailByPrimaryKey(ids[i]);
				TCMmLoanDetailDTO loanDto = new TCMmLoanDetailDTO();
				try {
					SimpleBeanUtils.copyBean2Bean(loanDto, quotaLoanDetailDTO);
					// BeanUtilsEx.copyProperties(loanDto, quotaLoanDetailDTO) ;
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				loanDto.setId(null);
				loanDto.setDealCode(dealdto.getDealCode());
				loanDto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_URL);
				loanDto.setCooperorgCode(dealdto.getCooperorgCode());
				loanDto.setLoanStatus(CimsConstant.LOAN_WAY); // 贷款读过来初始状态 为在途
				loanDto.setProductType(qloandto.getProductType());
				loanDto.setCreditPackageName(qloandto.getCreditPackageName()); //包名
				loanDto.setPlanRedeemDate(qloandto.getPlanRedeemDate());//计划赎回日期
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("dto", loanDto);
				lddao.insertTCMmLoanDetail(paramMap);
			}
		}
	}
	/**
	 * 按照额度编号创建贷款交易,按贷款的额度申请明细表的状态，然后插入到贷款明细表
	 */
	public void saveLoanDealDetailByQuota(QuotaLoanDto qloandto, TCMmCooperorgDealDTO dealdto) throws Exception {
		
		Map<String , Object> paramMap = new HashMap<String , Object>();
		TCMmQuotaLoanDetailDTO dto = new TCMmQuotaLoanDetailDTO();
		dto.setQuotaCode(qloandto.getQuotaCode());
		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);
		paramMap.put("dto", dto);
		List<TCMmQuotaLoanDetailDTO> qlist = qldao.searchTCMmQuotaLoanDetail(paramMap);
		if(qlist!=null&&qlist.size()>0){
			dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_LOCK);
			this.updateTCMmQuotaLoanDetailStatusByQuota(paramMap);
			for (TCMmQuotaLoanDetailDTO tcMmQuotaLoanDetailDTO : qlist) {
				TCMmLoanDetailDTO loanDto = new TCMmLoanDetailDTO();
				try {
					SimpleBeanUtils.copyBean2Bean(loanDto, tcMmQuotaLoanDetailDTO);
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				loanDto.setId(null);
				loanDto.setDealCode(dealdto.getDealCode());
				loanDto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_URL);
				loanDto.setCooperorgCode(dealdto.getCooperorgCode());
				loanDto.setLoanStatus(CimsConstant.LOAN_WAY); // 贷款读过来初始状态 为在途
				Map<String, Object> tparamMap = new HashMap<String, Object>();
				tparamMap.put("dto", loanDto);
				lddao.insertTCMmLoanDetail(tparamMap);
			}
		}else{
			throw new CimsException("该额度下没有贷款信息！");
		}
		
	}

	/**
	 * 更新债权明细的包信息
	 * 
	 * @author zhiqiang
	 * @description:
	 * @date 2015-01-12 20:34:29
	 * @param paramMap
	 */
	public void updateCreditDetailPackgeName(DealDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.updateCreditDetailPackgeName(paramMap);
	}
	
	/**
	 * 更新交易流水交互状态
	 * @param dto
	 * @throws Exception
	 */
	public void updateLoanEachStatusByDealCode(DealDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.updateLoanEachStatusByDealCode(paramMap);
	}
	
	/**
	 * 更新债权明细交互状态
	 * @param dto
	 * @throws Exception
	 */
	public void updateCreditDetailEachType(DealDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.updateCreditDetailEachType(paramMap);
	}
	
	/**
	 * 更新贷款明细交互状态
	 * @param dto
	 * @throws Exception
	 */
	public void updateLoanDetailEachType(DealDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.updateLoanDetailEachType(paramMap);
	}

	/**
	 * 更新贷款明细的包信息
	 * 
	 * @author zhiqiang
	 * @description:
	 * @date 2015-01-12 20:34:29
	 * @param paramMap
	 */
	public void updateLoanDetailPackgeName(DealDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.updateLoanDetailPackgeName(paramMap);
	}

	/**
	 * 更新贷款明细的包信息,账单日作为包号
	 * 
	 * @author zhiqiang
	 * @description:
	 * @date 2015-01-12 20:34:29
	 * @param paramMap
	 */
	public void updateLoanDetailPackgeNameByBill(DealDto dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.updateLoanDetailPackgeNameByBill(paramMap);
	}

	/**
	 * 更新交易状态
	 * 
	 * @Title updateDealStatus
	 * @Description TODO
	 * @param dto
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-2-8-下午5:43:32
	 * @update
	 * @throws
	 */
	public void updateDealStatus(TCMmCooperorgDealDTO dto) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
		cooperorgDealDTO.setDealCode(dto.getDealCode());
		map.put("dto", cooperorgDealDTO);
		cooperorgDealDTO = cooperorgDealService.searchTCMmCooperorgDeal(map).get(0);
		if (CimsConstant.DEAL_STATUS_CREATE.equals(cooperorgDealDTO.getCooperativeAgencyDealStatus())) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("dto", dto);
			dealDao.updateDealStatus(paramMap);// 更新交易流水状态
			/*
			 * Map<String, Object> paramMap2 = new HashMap<String, Object>();
			 * dto
			 * .setCooperativeAgencyDealStatus(CimsConstant.CREDIT_STATUS_WAY);
			 * paramMap2.put("dto", dto);
			 * dealDao.updateCreditDetailStatusForExport(paramMap2);//更新债权明细债权状态
			 */}
	}
	
	
	/**
	 * 更新交易状态
	 * 
	 * @Title updateDealStatus
	 * @Description TODO
	 * @param dto
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-2-8-下午5:43:32
	 * @update
	 * @throws
	 */
	public void updateDealStatusByDeal(TCMmCooperorgDealDTO dto) throws Exception {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("dto", dto);
			dealDao.updateDealStatus(paramMap);// 更新交易流水状态
	}
	
	/**
	 * 根据流水号更改流水状态
	 * @param dto
	 * @throws Exception
	 */
	public void updateDealStatusByDealCode(TCMmCooperorgDealDTO dto) throws Exception {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("dto", dto);
			dealDao.updateDealStatus(paramMap);// 更新交易流水状态
	}

	/**
	 * 
	 * @Title confirmCreditDealDetailResult
	 * @Description TODO
	 * @param creditDealList
	 * @throws Exception
	 *             void
	 * @author lizhiqiang
	 * @date 2015-3-26-下午3:10:15
	 * @update
	 * @throws
	 */
	public List<CreditDetailDto> doConfirmCreditDealDetailResult(List<CreditDetailDto> creditDealList) throws Exception {
		List<CreditDetailDto> resultRreditDealList = new ArrayList<CreditDetailDto>();
		
		for (CreditDetailDto creditDetailDto : creditDealList) {
			
			//计划赎回日期非空验证
	        if(creditDetailDto.getPlanRedeemDate()==null){
				throw new Exception("计划赎回日期不能为空！");
	        }
	        
			//当交互状态不等于  02已卖出,03  取消  05赎回  返回 空值！
			if (!("02").equals(creditDetailDto.getDealCreditorStatus()) && !("03").equals(creditDetailDto.getDealCreditorStatus())) {
				continue;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
			dto.setTransferId(creditDetailDto.getTransferId());
			map.put("dto", dto);
			List<TCMmCreditDetailDTO> list = creditDetailDao.searchTCMmCreditDetail(map);
			if (list.size() > 0) {
				dto = list.get(0);
				// 当合作机构债权状态 等于 在途（01）
				if (CimsConstant.CREDIT_STATUS_WAY.equals(dto.getCreditorStatus())) {
					resultRreditDealList.add(creditDetailDto);
				}
			}
		}
		if (resultRreditDealList.size() > 0) {
			return resultRreditDealList;
		}else{
			return null;
		}

	}
	
	/**
	 * 导入更新结算 费用
	 * @throws Exception
	 * 
	 * @Title updateCreditDealDetailToCostFee
	 * @Description TODO
	 * @param busiNoForInteract
	 * @param creditDealList
	 *            void
	 * @author zhoupeng
	 * @date 2016-4-14-下午4:50:34
	 * @update
	 * @throws
	 */
	public void updateCreditDealDetailToCostFee(List<CreditDetailDto> creditDetailList,String dealCode) throws Exception {
		if (creditDetailList.size() > 0) {
			for (CreditDetailDto creditDetailDto : creditDetailList) {
						Map<String, Object> paramMap = new HashMap<String, Object>();
						CreditDetailDto dto = new CreditDetailDto();
		    	        TCMmCreditDealDetailDTO creditDealDetaildto = new TCMmCreditDealDetailDTO();
						creditDealDetaildto.setTransferId(creditDetailDto.getTransferId());
						creditDealDetaildto.setDealStreamCode(dealCode);
						Map<String, Object> searchParamsdeal = new HashMap<String, Object>();
						searchParamsdeal.put("dto", creditDealDetaildto);
						List<TCMmCreditDealDetailDTO> tCMmCreditDealDetailDTO  = creditDealDetailDao.searchTCMmCreditDealDetail(searchParamsdeal);
						if(tCMmCreditDealDetailDTO.size()>0)
							creditDealDetaildto = tCMmCreditDealDetailDTO.get(0);
						// 根据债权转让编号和交易流水号修改债权价值
		    	        dto.setTransferId(creditDetailDto.getTransferId()); //转让编号
		    	        dto.setDealCode(dealCode); //交易流水号
		    	        dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN); //交易状态
		    	        if(creditDetailDto.getServiceCharge()==null){
		    	        	dto.setServiceCharge(BigDecimal.ZERO);//服务费
		    	        }else{
		    	        	dto.setServiceCharge(creditDetailDto.getServiceCharge());//服务费	
		    	        }
		    	        if(creditDetailDto.getGuaranteeFee()==null){
		    	        	dto.setGuaranteeFee(BigDecimal.ZERO);//担保费
		    	        }else{
		    	        	 dto.setGuaranteeFee(creditDetailDto.getGuaranteeFee());//担保费
		    	        }
		    	        if(creditDetailDto.getCautionMoney()==null){
		    	        	dto.setCautionMoney(BigDecimal.ZERO);//保证金
		    	        }else{
		    	        	dto.setCautionMoney(creditDetailDto.getCautionMoney());//保证金
		    	        }
		    	        //转让债权价值
		    	        if(creditDetailDto.getMakeCreditorValue()==null){
		    	        	dto.setMakeCreditorValue(BigDecimal.ZERO);//转让债权价值
		    				throw new Exception("转让债权价值MakeCreditorValue不能为空！");
		    	        }else{
		    	        	dto.setMakeCreditorValue(creditDetailDto.getMakeCreditorValue());//转让债权价值
		    	        }
		    	        dto.setCostState(creditDetailDto.getCostState());//导入的结算状态
		    	        paramMap.put("dto", dto);
		    	        //dto.setBackFee(creditDetailDto.getBackFee());//退费金额
		    	        //待结算或者未结算 才更新 导入的数据
		    	        logger.info("zhoupcs3 导入数据的状态为::" + creditDealDetaildto.getCostState());
						if(CimsConstant.COST_STATUS_DJ.equals(creditDealDetaildto.getCostState())||CimsConstant.COST_STATUS_WJ.equals(creditDealDetaildto.getCostState())||CimsConstant.COST_STATUS_BH.equals(creditDealDetaildto.getCostState())){
							logger.info("zhoupcs4 dto:*保证金:" + dto.getCautionMoney()+"dto:*担保费:" + dto.getGuaranteeFee()+"dto:*服务费:" + dto.getServiceCharge());
							logger.info("执行updateCreditDealDetailMakeCostFee Begin****" );
							dealDao.updateCreditDealDetailMakeCostFee(paramMap);
							dealDao.updateCreditDetailMakeCostFee(paramMap);
							logger.info("zhoupcs5 执行updateCreditDealDetailMakeCostFee End****" );
						}
						
				
			}
			Map<String, Object> paramMapdealCode = new HashMap<String, Object>();
	        // 根据交易流水号修改交易流水下的  总费用价值
			paramMapdealCode.put("dealStreamCode", dealCode); //交易流水号
			dealDao.updateCooperOrgDerailMakeCostFee(paramMapdealCode);
			
		}
	}
	
	/**
	 * 导入更新结算 费用
	 * @throws Exception
	 * 
	 * @Title updateCreditDealDetailToCostFee
	 * @Description TODO
	 * @param busiNoForInteract
	 * @param creditDealList
	 *            void
	 * @author zhoupeng
	 * @date 2016-4-14-下午4:50:34
	 * @update
	 * @throws
	 */
	public void updateCreditDealDetailToCostbackFee(List<CreditDetailDto> creditDetailList) throws Exception {
		if (CollectionsUtils.isEmpty(creditDetailList))  {
			return;
		}
		
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			creditDetailDto.setCostState(creditDetailDto.getSettlementSignName());
			if (CimsConstant.COST_STATUS_DJ.equals(creditDetailDto.getCostState()) 
					|| CimsConstant.COST_STATUS_WJ.equals(creditDetailDto.getCostState())
					|| CimsConstant.COST_STATUS_BH.equals(creditDetailDto.getCostState())) {
				if (!CreditPlanConstant.CHANGE_TYPE_ADVANCEFINISH.equals(creditDetailDto.getAbnormalSettle())) {
					creditDetailDto.setBackFee(BigDecimal.ZERO);
				}
				dealDao.updateCreditDealDetailMakeCostBackFee(SearchParamUtil.getSearchParam(creditDetailDto));
			}
		}
		
	}
	
	/**
	 * 更新债权计划赎回日期
	 * @Title updateCreditPlanRedeemDate
	 * @Description TODO
	 * @param creditDetailList
	 * @throws Exception 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-7-27-上午10:59:19
	 * @update 
	 * @throws
	 */
	public void updateCreditPlanRedeemDate(List<CreditDetailDto> creditDetailList) throws Exception {
		if (CollectionsUtils.isNotEmpty(creditDetailList))  {
			for (CreditDetailDto creditDetailDto : creditDetailList) {
				if(SimpleStringUtils.isEmpty(creditDetailDto.getTransferId())||SimpleStringUtils.isEmpty(creditDetailDto.getCreditCode())||creditDetailDto.getPlanRedeemDate()==null){
					throw new Exception("转让编号、债权编号、计划赎回日期不能为空！");
				}else{
					dealDao.updateCreditPlanRedeemDate(SearchParamUtil.getSearchParam(creditDetailDto));
				}
			}	
		}
	}
	/**
	 * 更新债权计划赎回日期
	 * @Title updateCreditPlanRedeemValue
	 * @Description TODO
	 * @param creditDetailList
	 * @throws Exception 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-7-28-下午4:57:11
	 * @update 
	 * @throws
	 */
	public void updateCreditPlanRedeemValue(TCMmCreditDetailDTO dto) throws Exception {
		//1、查询指定计划赎回日期的债权，查询100条
		List<TCMmCreditDetailDTO> list = dealDao.getCreditDetailListByPlanRedeemDate(SearchParamUtil.getSearchParam(dto));
		//5、跳出递归
		if(list!=null&&list.size()>0){
		//2、调用接口计算指定日期的债权价值
			List<TCMmCreditDetailDTO> updatelist = this.getCreditDetailRedemptionListByInterface(list);
		//3、批量更新计划赎回日期的债权价值
			dealDao.updateBatchCreditPlanRedeemValue(updatelist);
		//4、递归
			this.updateCreditPlanRedeemValue(dto);
		}
		
	}
	
	public List<TCMmCreditDetailDTO> getCreditDetailRedemptionListByInterface(List<TCMmCreditDetailDTO> creditDetailList) {

		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();

		CreditValueCalculateDto creditValueCalculateDto = new CreditValueCalculateDto();
		List<CreditValueCalculateDto.CreditValueCalculateBatch> batchIdList = new ArrayList<CreditValueCalculateDto.CreditValueCalculateBatch>();
		/* 保存执行上下文 */
		for (TCMmCreditDetailDTO creditDetail : creditDetailList) {
			CreditValueCalculateDto.CreditValueCalculateBatch cc = new CreditValueCalculateDto.CreditValueCalculateBatch();
			cc.setTransferId(creditDetail.getTransferId());
			cc.setCreidtId(creditDetail.getCreditCode());
			cc.setCreditDate(creditDetail.getPlanRedeemDate());
			cc.setEachRepaymentValue(creditDetail.getThisRepaySum());
			batchIdList.add(cc);
		}
		creditValueCalculateDto.setBatchIdList(batchIdList);
		creditValueCalculateDto.setDealCode(busiNoForInteract);
		logger.info("赎回调用4028："+JSON.toJSONString(creditValueCalculateDto));
		List<CreditValueCalculateResultDto> rslist = iCInteract.getCreditValue(creditValueCalculateDto);
		logger.info("赎回调用4028返回结果："+JSON.toJSONString(rslist));
		if (rslist == null) {
			return null;
		}
		Map<String, CreditValueCalculateResultDto> map = new HashMap<String, CreditValueCalculateResultDto>();
		for (CreditValueCalculateResultDto creditValueCalculateResultDto : rslist) {
			map.put(creditValueCalculateResultDto.getTransferId(), creditValueCalculateResultDto);
		}
		List<TCMmCreditDetailDTO> resultlist = new ArrayList<TCMmCreditDetailDTO>();
		for (TCMmCreditDetailDTO tcMmCreditDetailDTO : creditDetailList) {
			CreditValueCalculateResultDto creditValueCalculateResultDto = map.get(tcMmCreditDetailDTO.getTransferId());
			tcMmCreditDetailDTO.setThisMakeCreditorValue(creditValueCalculateResultDto.getCreditValue());
			resultlist.add(tcMmCreditDetailDTO);
		}
		return resultlist;
	}
	
	public DealDto TbjCooperorgDealData(String dealCode){
		Map<String, Object> searchParams = new HashMap<String, Object>();
		DealDto dto = new DealDto();
		dto.setDealCode(dealCode);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(new DataMsg());
		params.setPageParameter(pageInfo);
		List<DealDto> dealDtoList = this.getDealList(params.getSearchParams());
		DealDto dealDto = new DealDto();
		//获取我司原交易流水
		if(dealDtoList.size()>0){
			dealDto = dealDtoList.get(0);
		}
		
		return dealDto;
	}
	
	/**
	 * 铜板街拆包
	 * @param creditDealList
	 * @param dealCode
	 * @return
	 * @throws Exception
	 */
	public void doTbjCooperorgPackageName(List<CreditDetailDto> creditDealList,String dealCode,boolean flag) throws Exception {
		
		
		CreditDetailDto creditDetailDto = creditDealList.get(0);
		
		DealDto dealDto = this.TbjCooperorgDealData(dealCode);
		
		TCMmCreditPackageDTO creditPackageDTO = new TCMmCreditPackageDTO();

		// 创建交易流水信息
		StringBuffer dealCodesb = new StringBuffer();
		this.doGetDealCode(dealCodesb);
		String dealCodeNew = dealCodesb.toString();
		dealDto.setDealCode(dealCodeNew);// 交易流水号
		dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_WAY);// 在途
		dealDto.setCreditPackageName(creditDetailDto.getCooperorgPackageName()); // 拆包后的包名
		dealDto.setDealDate(new Date());
		
		
		if (flag) {
			// 保存包信息
			creditPackageDTO.setCooperorgCode(dealDto.getCooperorgCode());// 机构编号
			creditPackageDTO.setContractCode(dealDto.getContractCode());// 合约编号
			creditPackageDTO.setCreditPackageName(creditDetailDto.getCooperorgPackageName());// 包号
			creditPackageDTO.setBillDate(dealDto.getBillDate());
			creditPackageDTO.setBillDateEnd(dealDto.getBillDateEnd());
			creditPackageDTO.setRepayType(dealDto.getRepayType());
			creditPackageService.insertTCMmCreditPackage(creditPackageDTO);
			creditPackageDTO=null;
		}
	
		TCMmCreditDealDetailDTO tCMmCreditDealDetailDTO = new TCMmCreditDealDetailDTO();
		CreditDetailDto creditDetailDtoUpdate = new CreditDetailDto();
		BigDecimal sumCreditorValue = new BigDecimal(0);//汇总债权价值
		for (CreditDetailDto creditDetail : creditDealList) {
			
			sumCreditorValue = sumCreditorValue.add(creditDetail.getThisMakeCreditorValue());
			//更新交易流水明细表
			tCMmCreditDealDetailDTO.setTransferId(creditDetail.getTransferId());//债权转让编号
			tCMmCreditDealDetailDTO.setDealStreamCodeTbj(dealCodeNew);///铜板街拆包后的流水号
			tCMmCreditDealDetailDTO.setDealStreamCode(dealCode);//我司交易流水号
			int count = tCMmCreditDealDetailService.updateTCMmCreditDealDetailByTransferId(tCMmCreditDealDetailDTO);
			
			if(count>0){
				//更新债权明细表
				creditDetailDtoUpdate.setTransferId(creditDetail.getTransferId());//债权转让编号
				creditDetailDtoUpdate.setPackageNum(creditDetail.getCooperorgPackageName());//修改债权包为机构理财包名
				creditDetailDtoUpdate.setCooperorgPackageName(creditDetail.getPackageNum());//机构理财原包名
				tCMmCreditDetailService.updateTCMmCreditDetailByTransferId(creditDetail);
			}
		}
		dealDto.setSumCreditorValue(sumCreditorValue);
		cooperorgDealService.insertTCMmCooperorgDeal(dealDto);//创建新的交易流水
		
		
		Map<String, Object> searchParams = new HashMap<String, Object>();
		DealDto dealDtoOld = this.TbjCooperorgDealData(dealCode);//查询旧的的交易流水
		searchParams.put("dto", dealDtoOld);
		CreditRightDto creditRightDto = this.getDealDetailByCreditListByTotal(searchParams);
		dealDtoOld.setSumCreditorValue(creditRightDto.getSumCreditorValue());
		cooperorgDealService.updateTCMmCooperorgDeal(dealDtoOld);
		
		tCMmCreditDealDetailDTO=null;
		creditDetailDtoUpdate = null;

		dealDto=null;
		dealDtoOld = null;
		
	}

	/**
	 * @throws Exception
	 * 
	 * @Title doRegisterUpdateCreditDealDetailResult
	 * @Description TODO
	 * @param busiNoForInteract
	 * @param creditDealList
	 *            void
	 * @author lizhiqiang
	 * @date 2015-3-26-下午3:10:34
	 * @update
	 * @throws
	 */
	public void doRegisterUpdateCreditDealDetailResult(String busiNoForInteract, List<CreditDetailDto> creditDealList,String cooperorgCode,String creditAffiliation,String dealCode) throws Exception {
		

		List<CreditDetailDto> resultList = doConfirmCreditDealDetailResult(creditDealList);
		if(!CollectionsUtils.isEmpty(resultList)){
			
			if(cooperorgCode.equals(CimsConstant.TBJ_COOPERORG_CODE)){
				
				this.doImportCheckTbj(busiNoForInteract,resultList,creditDealList,dealCode,creditAffiliation);
			}else{
				this.sureCreditDataInfo(busiNoForInteract, resultList, creditDealList, cooperorgCode, creditAffiliation, dealCode);
			}
		}else{
			this.sureCreditDataInfo(busiNoForInteract, resultList, creditDealList, cooperorgCode, creditAffiliation, dealCode);
		}
		

		
	}
	
	public void sureCreditDataInfo(String busiNoForInteract,List<CreditDetailDto> resultList,List<CreditDetailDto> creditDealList,String cooperorgCode,String creditAffiliation,String dealCode)throws Exception{
		logger.info("zhoupcs 2 调用updateCreditDealDetailToCostFee方法开始:流水号为" + dealCode+";creditDealList:"+creditDealList.size());
		//跟新结算状态
		this.updateCreditDealDetailToCostFee(creditDealList,dealCode);
		logger.info("zhoupcs 6 调用updateCreditDealDetailToCostFee方法结束:流水号为" + dealCode+";creditDealList:"+creditDealList.size());
		//过滤未打标记的，只处理在途的
		if(resultList!=null&&resultList.size()>0){
			logger.info("处理在途信息开始 流水号为" + dealCode+";creditDealList:"+creditDealList.size());
			//更新本地流水明细
			this.doExcelImport(resultList);
			//更新交易流水状态
			this.updateCooperDealStatus(dealCode);
			//调用核心接口 释放或者确认
			this.updateCreditDealDetailResult(resultList, busiNoForInteract, cooperorgCode, creditAffiliation, dealCode);

		}
		logger.info("处理在途信息结束 流水号为" + dealCode+";creditDealList:"+creditDealList.size());
		
	}

	/**
	 * @throws Exception 
	 * 根据交易流水明细的状态更新交易流水状态
	 * @Title updateCooperDealStatus
	 * @Description TODO
	 * @param dealcode 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-5-11-下午4:58:41
	 * @update 
	 * @throws
	 */
	public void updateCooperDealStatus(String dealCode) throws Exception{
		//查询流水下是否还有在途的债权
		int  creditCount = dealDao.selectCreditInWayByDealCode(dealCode);
		if(creditCount==0){
			TCMmCooperorgDealDTO dto = new TCMmCooperorgDealDTO();
			dto.setDealCode(dealCode);
			dto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);// 03 交易完成
			this.updateDealStatusByDealCode(dto);
		}
	}

	/**
	 * 更新导入结果
	 * 
	 * @Title updateCreditDealDetailToCreditDetail
	 * @Description TODO void
	 * @author lizhiqiang
	 * @date 2015-2-8-下午6:24:23
	 * @update
	 * @throws
	 */
	public void updateCreditDealDetailResult(List<CreditDetailDto> creditDetailList, String busiNoForInteract,String cooperorgCode,String creditAffiliation,String dealCode) {
		if (creditDetailList.size() > 0) {
			List<QuotaDetailUnlockParamDto.CreditRightUnlockInfo> creditRightUnlockInfoList = new ArrayList<QuotaDetailUnlockParamDto.CreditRightUnlockInfo>();
			List<ConfirmParamDto.CreditRightInfo> creditRightInfoList = new ArrayList<ConfirmParamDto.CreditRightInfo>();
			for (CreditDetailDto creditDetailDto : creditDetailList) {
				if (CimsConstant.CREDIT_STATUS_LOSE.equals(creditDetailDto.getDealCreditorStatus())) {
					QuotaDetailUnlockParamDto.CreditRightUnlockInfo creditRightUnlockInfo = new QuotaDetailUnlockParamDto.CreditRightUnlockInfo();
					creditRightUnlockInfo.setCreditId(creditDetailDto.getCreditCode());// 债权编号
					creditRightUnlockInfo.setTransferId(creditDetailDto.getTransferId());// 转让编号
//					creditRightUnlockInfo.setEachRepaymentValue(creditDetailDto.getThisRepaySum());// //本次释放对应月还金额(本期还款金额)
					creditRightUnlockInfo.setContractNo(creditDetailDto.getCreditCode());
					creditRightUnlockInfo.setFreeValue(creditDetailDto.getThisMakeCreditorValue());// 本次释放债权价值（本次转让债权价值）
					creditRightUnlockInfo.setIsWhole(CimsConstant.CREDIT_ISWHOLE);// 全部释放
					creditRightUnlockInfoList.add(creditRightUnlockInfo);
				} else if (CimsConstant.CREDIT_STATUS_WIN.equals(creditDetailDto.getDealCreditorStatus())) {
					ConfirmParamDto.CreditRightInfo creditRightInfo = new ConfirmParamDto.CreditRightInfo();
					creditRightInfo.setCreditId(creditDetailDto.getCreditCode());// 协议编号
					creditRightInfo.setTransferId(creditDetailDto.getTransferId());// 转让编号
//					creditRightInfo.setSureValue(creditDetailDto.getThisMakeCreditorValue());// 本次确认债权价值
//					creditRightInfo.setEachRepaymentValue(creditDetailDto.getThisRepaySum());// 本次确认对应月还金额
					creditRightInfo.setDeliveryDate(creditDetailDto.getDeliverDate());// 交割日期
					creditRightInfo.setContractNo(creditDetailDto.getCreditCode());
					creditRightInfoList.add(creditRightInfo);
				}
			}
			if (creditRightUnlockInfoList.size() > 0) {
				QuotaDetailUnlockParamDto paramDto = new QuotaDetailUnlockParamDto();
				paramDto.setQuotaType(CimsConstant.QUOTATYPE_CR);
				paramDto.setCreditRightUnlockList(creditRightUnlockInfoList);
				paramDto.setDealCode(busiNoForInteract);
				// 调用释放债权的接口
				iCInteract.quotaDetailUnlock(paramDto);
			}
			if (creditRightInfoList.size() > 0) {
				// 债权审批确认
				ConfirmParamDto confirmParamDto = new ConfirmParamDto();
				confirmParamDto.setBusiType(CimsConstant.QUOTATYPE_CR);
				confirmParamDto.setCreditRightList(creditRightInfoList);
				confirmParamDto.setDealCode(busiNoForInteract);
				confirmParamDto.setCooperorgCode(cooperorgCode);
				confirmParamDto.setCreditAffiliation(creditAffiliation);
				iCInteract.approveConfrim(confirmParamDto);
				
				//修改月还归属
				confirmParamDto = new ConfirmParamDto();
				confirmParamDto.setCreditRightList(creditRightInfoList);
				confirmParamDto.setDealCode(dealCode);
				confirmParamDto.setCreditAffiliation(creditAffiliation);
				creditDealDetailDaos.updateRepayAffiliationForEach(SearchParamUtil.getSearchParam(confirmParamDto));
			}
		}

	}

	/**
	 * 根据债权包查询债权
	 * 
	 * @Title getDealDetailByPackage
	 * @Description TODO
	 * @param paramMap
	 * @return List<TCMmCreditDetailDTO>
	 * @author lixinyao
	 * @date 2015-3-3-下午3:32:42
	 * @update
	 * @throws
	 */
	public List<CreditDetailDto> getDealDetailByPackage(Map<String, Object> paramMap) {
		return dealDao.getDealDetailByPackage(paramMap);
	}

	/**
	 * 根据债权包分页查询债权
	 * 
	 * @Title getDealDetailByPackage
	 * @Description TODO
	 * @param paramMap
	 * @return List<TCMmCreditDetailDTO>
	 * @author lixinyao
	 * @date 2015-3-3-下午3:32:42
	 * @update
	 * @throws
	 */
	public List<CreditDetailDto> getDealDetailByPackageByPaging(Map<String, Object> paramMap) {
		return dealDao.getDealDetailByPackageByPaging(paramMap);
	}

	/**
	 * @Description 根据业务流水号执行接口信息
	 * 
	 * @param businessCode
	 *            业务流水号
	 * @throws Exception
	 */
	public void doInteractClassInvokeByBusinessCode(String businessCode) throws Exception {
		interactClassInvokeService.exeInteractClassInvokeByBusinessCode(businessCode);
	}

	/**
	 * @Description 批量查询合作机构交易流水信息
	 * @author shengzhoutao
	 * @param dealCodeStr
	 *            交易流水号字符串，多个交易流水号以逗号分隔开
	 * @return List<DealDto> 交易流水信息集合
	 */
	public List<DealDto> getCooperorgDealByDealCodeStr(String dealCodeStr) {
		if (!SimpleStringUtils.hasText(dealCodeStr)) {
			return null;
		}

		String[] dealCodeArr = dealCodeStr.split(",");

		List<String> dealCodeList = new ArrayList<String>();
		CollectionUtils.addAll(dealCodeList, dealCodeArr);

		return dealDao.getCooperorgDealByDealCodeList(dealCodeList);
	}

	/**
	 * @Description 批量查询合作机构交易流水信息
	 * @author shengzhoutao
	 * @param dealCodeList
	 *            交易流水号
	 * @return List<DealDto> 交易流水信息集合
	 */
	public List<DealDto> getCooperorgDealByDealCodeList(List<String> dealCodeList) {
		logger.info("dealCodeList::" + dealCodeList);
		if (CollectionsUtils.isEmpty(dealCodeList)) {
			return null;
		}

		return dealDao.getCooperorgDealByDealCodeList(dealCodeList);
	}

	/**
	 * @Description 批量修改交易状态
	 * @author shengzhoutao
	 * @param dealStatus
	 *            要修改的交易状态
	 * @param dealCodeList
	 *            存放要修改的多个交易流水号的集合
	 */
	public void updateDealStatusByDealCodeList(String dealStatus, List<String> dealCodeList) {
		logger.info("要修改的交易状态::" + dealStatus);
		logger.info("存放要修改的多个交易流水号::" + CollectionsUtils.convertToString(dealCodeList, ","));
		if (CollectionsUtils.isEmpty(dealCodeList) || !SimpleStringUtils.hasText(dealStatus)) {
			return;
		}

		DealDto dealDto = new DealDto();
		dealDto.setCooperativeAgencyDealStatus(dealStatus);
		dealDto.setDealCodeList(dealCodeList);
		dealDao.updateDealStatusByDealCodeList(SearchParamUtil.getSearchParam(dealDto));

		dealDto = null;
	}

	/**
	 * 数据字典码值取名称
	 * 
	 * @Title getDictDetailName
	 * @Description TODO
	 * @param dict_code
	 * @param detail_value
	 * @return String
	 * @author lizhiqiang
	 * @date 2015-4-9-下午4:40:07
	 * @update
	 * @throws
	 */
	public String getDictDetailName(String dict_code, String detail_value) {
		String dictDetailName = "";
		if (!SimpleStringUtils.isBlank(dict_code) && !SimpleStringUtils.isBlank(detail_value)) {
			SysDictDetailVo sysDictDetailVo = sysDictAPI.queryDetailByDictCodeAndDeatailValue(dict_code, detail_value);
			if (sysDictDetailVo != null)
				dictDetailName = sysDictDetailVo.getDictDetailName();
		}
		return dictDetailName;
	}
	/**
	 * 缓存数据字典
	 * @Title getDictDetailName
	 * @Description TODO
	 * @param dict_code
	 * @return 
	 * Map 
	 * @author lizhiqiang
	 * @date 2016-9-27-上午9:37:51
	 * @update 
	 * @throws
	 */
	public Map<String,String> getDictDetailName(String dict_code) {
		List<Map> resultMap = sysDictDetailService.queryDetailByDictCode(dict_code);
		Map<String,String> dictmap = new HashMap<String,String>();
		if(CollectionsUtils.isNotEmpty(resultMap)){
			for (Map map : resultMap) {
				if(map.get("DICVALUE")!=null&&map.get("DICNAME")!=null)
				dictmap.put(map.get("DICVALUE").toString(), map.get("DICNAME").toString());
			}
		}
		return dictmap;
	}
	/**
	 * 
	 * @Description 
	 * @param dict_code
	 * @param detail_value
	 * @return   
	 * String  
	 * @throws
	 * @author zhangmi
	 * @date 2016-6-8
	 */
	public String tbjGetDictDetailName(String dict_code, String detail_value){
		String dictDetailName = "";
		if (!SimpleStringUtils.isBlank(dict_code) && !SimpleStringUtils.isBlank(detail_value)) {
			DictDetailDto dto = new DictDetailDto();
			dto.setDictCode(dict_code);
			dto.setDictDetailValue(detail_value);
			List<DictDetailDto> list = dictDetailDao.getDictDetailDtoByCode(SearchParamUtil.getSearchParam(dto));
			if(CollectionsUtils.isNotEmpty(list)){
				dictDetailName = list.get(0).getTbjDictDetailName();
			}
		}
		return dictDetailName;
	}
	/**
	 * 铜板街数据字典缓存
	 * @Title tbjGetDictDetailName
	 * @Description TODO
	 * @param dict_code
	 * @return 
	 * String 
	 * @author lizhiqiang
	 * @date 2016-9-27-上午10:11:00
	 * @update 
	 * @throws
	 */
	public Map<String ,String> tbjGetDictDetailName(String dict_code){
		Map<String,String> dictmap = new HashMap<String,String>();
		if (!SimpleStringUtils.isBlank(dict_code)) {
			DictDetailDto dto = new DictDetailDto();
			dto.setDictCode(dict_code);
			List<DictDetailDto> list = dictDetailDao.getDictDetailDtoByCode(SearchParamUtil.getSearchParam(dto));
			if(CollectionsUtils.isNotEmpty(list)){
				for (DictDetailDto dictDetailDto : list) {
					dictmap.put(dictDetailDto.getTbjDictDetailValue(), dictDetailDto.getTbjDictDetailName());
				}
			}
		}
		return dictmap;
	}
	
	/**
	 * 生成包规则为账单日的包信息
	 * 
	 * @Title insertCreditPackageByBillDay
	 * @Description TODO
	 * @param dto
	 * void
	 * @author lizhiqiang
	 * @date 2015-4-10-下午2:30:32
	 * @update
	 * @throws
	 */
	public void insertCreditPackageByBillDay(DealDto dto) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		dealDao.insertCreditPackageByBillDay(paramMap);
	}

	/**
	 * @author zhiqiang
	 * @description: 按条件查询债权包列表
	 * @date 2015-01-07 16:20:41
	 * @param searchParams
	 *            条件
	 * @return
	 * @throws
	 */
	public List<TCMmCreditPackageDTO> searchTCMmCreditPackage(Map<String, Object> searchParams) throws Exception {
		if ("credit".equals(searchParams.get("pagType"))) {
			List<TCMmCreditPackageDTO> dataList = dealDao.searchCreditPackageByCredit(searchParams);
			return dataList;
		} else {
			List<TCMmCreditPackageDTO> dataList = dealDao.searchCreditPackageByLoan(searchParams);
			return dataList;
		}
	}

	/**
	 * @description 保存交易流水
	 * @author shengzhoutao
	 * @param dealDto
	 * @return id
	 */
	public long saveDeal(DealDto dealDto) throws Exception {
		return cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
	}
	/**
	 * @description 保存交易流水并保存赎回明细
	 * @author lizhiqiang
	 * @param dealDto
	 * @return id
	 */
	public long saveTransferRedempDeal(DealDto dealDto) throws Exception {
		
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dealDto);
		List<CreditDetailDto> creditList = this.getDealCreditDetailByPackageAll(searchParams);
		
		List<TCMmCreditDealDetailDTO> creditDealDetailDTOList = new ArrayList<TCMmCreditDealDetailDTO>();
		BigDecimal sumCreditValue = new BigDecimal("0");
		int creditCount = 0;
		for (CreditDetailDto creditDetailDto : creditList) {
			TCMmCreditDealDetailDTO cdd = new TCMmCreditDealDetailDTO();
			cdd.setDealStreamCode(dealDto.getDealCode());
			cdd.setCooperorgCode(dealDto.getCooperorgCode());
			cdd.setTransferId(creditDetailDto.getTransferId());
			cdd.setThisMakeCreditorValue(creditDetailDto.getThisMakeCreditorValue());
			//cdd.setMakeCreditorValue(creditDetailDto.getMakeCreditorValue());
			//cdd.setRedeemDate(dealDto.getRedemptionDate());
			
			sumCreditValue = sumCreditValue.add(creditDetailDto.getThisMakeCreditorValue());
			creditCount++;
			creditDealDetailDTOList.add(cdd);
		}
		
		// 批量新增债权流水
		batchService.batchInvoke(CCreditRightImpl.class, "insertCreditDealDetailByBatch", creditDealDetailDTOList, null, 100);
		//creditRight.insertCreditDealDetailByBatch(creditDealDetailDTOList);
		
		dealDto.setSumCreditorValue(sumCreditValue);
		dealDto.setDetialNumber(creditCount);
		dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);
		dealDto.setCreateTime(new Timestamp(System.currentTimeMillis()));
		dealDto.setDealType(CimsConstant.DEAL_TYPE_TRANSFER_CREDIT_REDEEM);
		dealDto.setDealDate(new Date());
		dealDto.setAgreementCode(dealDto.getAgreementCode());
		dealDto.setRedemptionDate(dealDto.getRedemptionDate());
		return cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
	}
	
	/**
	 * @description 通过债权明细保存交易流水并保存赎回明细
	 * @param dealDto
	 * @return id
	 */
	public long saveTransferRedempDealBycreditDetail(DealDto dealDto,List<CreditDetailDto> creditList) throws Exception {
				
		List<TCMmCreditDealDetailDTO> creditDealDetailDTOList = new ArrayList<TCMmCreditDealDetailDTO>();
		BigDecimal sumCreditValue = new BigDecimal("0");
		int creditCount = 0;
		for (CreditDetailDto creditDetailDto : creditList) {
			TCMmCreditDealDetailDTO cdd = new TCMmCreditDealDetailDTO();
			cdd.setDealStreamCode(dealDto.getDealCode());
			cdd.setCooperorgCode(dealDto.getCooperorgCode());
			cdd.setTransferId(creditDetailDto.getTransferId());
			cdd.setThisMakeCreditorValue(creditDetailDto.getThisMakeCreditorValue());
			//cdd.setMakeCreditorValue(creditDetailDto.getMakeCreditorValue());
			//cdd.setRedeemDate(dealDto.getRedemptionDate());
			
			sumCreditValue = sumCreditValue.add(creditDetailDto.getThisMakeCreditorValue());
			creditCount++;
			creditDealDetailDTOList.add(cdd);
		}
		
		// 批量新增债权流水
		batchService.batchInvoke(CCreditRightImpl.class, "insertCreditDealDetailByBatch", creditDealDetailDTOList, null, 100);
		//creditRight.insertCreditDealDetailByBatch(creditDealDetailDTOList);
		
		dealDto.setSumCreditorValue(sumCreditValue);
		dealDto.setDetialNumber(creditCount);
		dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);
		dealDto.setCreateTime(new Timestamp(System.currentTimeMillis()));
		dealDto.setDealType(CimsConstant.DEAL_TYPE_TRANSFER_CREDIT_REDEEM);
		dealDto.setDealDate(new Date());
		dealDto.setAgreementCode(dealDto.getAgreementCode());
		dealDto.setRedemptionDate(dealDto.getRedemptionDate());
		return cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
	}

	/**
	 * 
	 * @Title doBatchConfirmTransferRedemp
	 * @Description TODO
	 * @param cdlist
	 * @param paramMap
	 * @throws Exception 
	 * void 
	 * @author lizhiqiang
	 * @date 2017-5-11-上午11:56:37
	 * @update 
	 * @throws
	 */
	public void doBatchConfirmTransferRedemp(List<CreditDetailDto> cdlist,Map<Object, Object> paramMap) throws Exception {
		batchService.batchInvoke(DealService.class, "doConfirmTransferRedemp", cdlist, paramMap, 20);
	}
	/**
	 * 
	 * @Title confirmTransferRedemp
	 * @Description TODO
	 * @param dealDto
	 * @return
	 * @throws Exception 
	 * long 
	 * @author lizhiqiang
	 * @date 2016-2-23-下午4:30:44
	 * @update 
	 * @throws
	 */
	public void doConfirmTransferRedemp(List<CreditDetailDto> cdlist,Map<Object, Object> paramMap) throws Exception {
		
		DealDto dealDto = (DealDto)paramMap.get("dto");
		RedeemParamDto redeemParamDto = new RedeemParamDto();
		
		List<TCMmCreditDetailDTO> tCMmCreditDetailDTOList = new ArrayList<TCMmCreditDetailDTO>();
		for (CreditDetailDto creditDetailDto : cdlist) {
			if(creditDetailDto.getCreditorStatus().equals(CimsConstant.CREDIT_STATUS_RED)){
				return;
			}
			TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
			dto.setTransferId(creditDetailDto.getTransferId());
			dto.setContractCode(dealDto.getContractCode());
			dto.setRedeemDate(creditDetailDto.getRedeemDate());
			tCMmCreditDetailDTOList.add(dto);
		}
		redeemParamDto.settCMmCreditDetailDTOList(tCMmCreditDetailDTOList);
		redeemParamDto.setCCode(dealDto.getCooperorgCode());
		redeemParamDto.setDealCode(dealDto.getDealCode());
		
		RedeemResultDto redeemResultDto = iCInteract.sendSrCreditorBatchRedeemToCore(redeemParamDto);
		//2、更新明细状态
		List<ResponseRedemptionCreditDTO> srTransferList = redeemResultDto.getSrTransferList();
		StringBuffer sb = new StringBuffer();
		for (ResponseRedemptionCreditDTO responseRedemptionCreditDTO : srTransferList) {
			sb.append("'").append(responseRedemptionCreditDTO.getCreditId()).append("',");
		}
		
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("ids", sb.deleteCharAt(sb.length()-1).toString());
		searchParams.put("status", CimsConstant.CREDIT_STATUS_RED);
		iCreditDetailDao.updateTCMmCreditDetailStatusByTransferId(searchParams);
		
		//3、更新流水状态
		TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
		cooperorgDealDTO.setDealCode(dealDto.getDealCode());
		cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);
		// 更新交易流水状态为在途
		this.updateDealStatusByDealCode(cooperorgDealDTO);
	}
	
	/**
	 * 选择赎回债权，转换指定日期的债权价值
	 * 
	 * @param creditDetailList
	 * @param redeemDate
	 * @return
	 */
	public List<CreditDetailDto> getCreditDetailRedemptionListByInterface(List<CreditDetailDto> creditDetailList, Date redeemDate) {

		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		iInteractAssist.registerDealIrtService(busiNoForInteract);

		CreditValueCalculateDto creditValueCalculateDto = new CreditValueCalculateDto();
		List<CreditValueCalculateDto.CreditValueCalculateBatch> batchIdList = new ArrayList<CreditValueCalculateDto.CreditValueCalculateBatch>();
		/* 保存执行上下文 */
		for (TCMmCreditDetailDTO creditDetail : creditDetailList) {
			CreditValueCalculateDto.CreditValueCalculateBatch cc = new CreditValueCalculateDto.CreditValueCalculateBatch();
			cc.setTransferId(creditDetail.getTransferId());
			cc.setCreidtId(creditDetail.getCreditCode());
			cc.setCreditDate(redeemDate);
			cc.setEachRepaymentValue(creditDetail.getThisRepaySum());
			batchIdList.add(cc);
		}
		creditValueCalculateDto.setBatchIdList(batchIdList);
		creditValueCalculateDto.setDealCode(busiNoForInteract);
		logger.info("赎回调用4028："+JSON.toJSONString(creditValueCalculateDto));
		List<CreditValueCalculateResultDto> rslist = iCInteract.getCreditValue(creditValueCalculateDto);
		logger.info("赎回调用4028返回结果："+JSON.toJSONString(rslist));
		if (rslist == null) {
			return null;
		}
		Map<String, CreditValueCalculateResultDto> map = new HashMap<String, CreditValueCalculateResultDto>();
		for (CreditValueCalculateResultDto creditValueCalculateResultDto : rslist) {
			map.put(creditValueCalculateResultDto.getTransferId(), creditValueCalculateResultDto);
		}
		List<CreditDetailDto> resultlist = new ArrayList<CreditDetailDto>();
		for (CreditDetailDto creditDetailDTO : creditDetailList) {
			CreditValueCalculateResultDto creditValueCalculateResultDto = map.get(creditDetailDTO.getTransferId());
			creditDetailDTO.setThisMakeCreditorValue(creditValueCalculateResultDto.getCreditValue());
			resultlist.add(creditDetailDTO);
		}
		return resultlist;
	}


	/**
	 * @description 查询交易流水
	 * @author shengzhoutao
	 * @param dealDto
	 * @return List<TCMmCooperorgDealDTO>
	 */
	public List<TCMmCooperorgDealDTO> searchDeal(DealDto dealDto) throws Exception {
		return cooperorgDealService.searchTCMmCooperorgDeal(SearchParamUtil.getSearchParam(dealDto));
	}
	
	/**
	 * 更新债权结算明细信息
	 */
	public void updateCreditSettle(String dealCode,String creditorStatus) throws Exception{
			Map<String, Object> paramMap  = new HashMap<String, Object>();
			paramMap.put("dealCode", dealCode);
			paramMap.put("creditorStatus", creditorStatus);
			dealDao.updateCreditSettle(paramMap);
		
	}
	
	/**
	 * 更新交易信息
	 */
	public void updateCreditDeal(String dealCode,String cooperativeAgencyDealStatus) throws Exception{
			Map<String, Object> paramMap  = new HashMap<String, Object>();
			paramMap.put("dealCode", dealCode);
			paramMap.put("cooperativeAgencyDealStatus", cooperativeAgencyDealStatus);
			dealDao.updateCreditDeal(paramMap);
	
	}

    /**
     * 获取贷款回购跨账单日结果列表
     * @throws Exception 
     * @Title getLoanTransferCrossBillDate
     * @Description TODO
     * @return 
     * @author yanjingying
     * @date 2015-12-29-下午18:47:00
     * @update
     * @throws
     * */
	public List<LoanTransferCrossBillDateDto> doLoanTransferCrossBillDate(TCMmCooperorgDealDTO cooperorgDealDTO) throws Exception{
		return loanRedeemService.getLoanTransferCrossBillDate(cooperorgDealDTO);
	}
	
	/**
	 * 根据交易流水号、债权来源、核心债权状态查询交易流水明细信息
     * @Title getDealDetailByCreditInfo
     * @Description TODO
     * @param searchParams 
     * void 
     * @author yanjingying
     * @date 2015-12-22-上午11:17:56
     * @update 
     * @throws
	 * */
	public List<TCMmCreditDealDetailDTO> getDealDetailByCreditInfo(Map<String, Object> searchParams) throws Exception{
		return dealDao.getDealDetailByCreditInfo(searchParams);
	}
	
	/**
	 * 根据交易流水号、债权转让编号【修改交易流水明细表的债权状态、更新时间】
     * @throws Exception 
     * @Title updateTcmmCreditDealCreditorStatusByDealStreamCode
     * @Description TODO
     * @return 
     * @author yanjingying
     * @date 2015-12-17-下午11:47:00
     * @update
     * @throws
	 * */
	public void updateTcmmCreditDealCreditorStatusByDealStreamCode(String dealStreamCode, String creditSource, 
			String[] coreCreditStatus, String[] creditStatus, String creditorStatus) throws Exception{
		logger.info(">>>>>>>>>>>>>>当前交易流水号："+dealStreamCode+">>>>>>>>>>>>>>");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("creditorStatus", creditorStatus);  //债权状态
		paramMap.put("dealStreamCode", dealStreamCode);  //交易流水号
		paramMap.put("creditSource", creditSource);      //债权来源 02-贷款 01-债权
		paramMap.put("coreCreditStatus", coreCreditStatus);  //核心债权状态
		paramMap.put("creditStatus", creditStatus);  //债权状态
		paramMap.put("redeemDate", new Date());   //赎回日期
		dealDao.updateTcmmCreditDealCreditorStatusByDealStreamCode(paramMap);
		
	} 
	
	/**
	 * 根据债权转让编号【修改债权明细表的债权状态、更新时间、赎回日期-确认日期】
     * @throws Exception 
     * @Title updateTcmmCreditCreditorStatusByDealStreamCode
     * @Description TODO
     * @return 
     * @author yanjingying
     * @date 2015-12-17-下午11:47:00
     * @update
     * @throws
	 * */
	public void updateTcmmCreditCreditorStatusByDealStreamCode(String dealStreamCode, String creditSource, 
			String[] coreCreditStatus, String[] creditStatus, String creditorStatus) throws Exception{
		logger.info(">>>>>>>>>>>>>>当前交易流水号："+dealStreamCode+">>>>>>>>>>>>>>");
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("creditorStatus", creditorStatus);  //债权状态
		paramMap.put("dealStreamCode", dealStreamCode);  //交易流水号
		paramMap.put("creditSource", creditSource);      //债权来源 02-贷款 01-债权
		paramMap.put("coreCreditStatus", coreCreditStatus);  //核心债权状态
		paramMap.put("creditStatus", creditStatus);  //债权状态
		paramMap.put("redeemDate", new Date());   //赎回日期
		dealDao.updateTcmmCreditCreditorStatusByDealStreamCode(paramMap);
		
	}
	
	/**
	 * 贷款回购交易两个事务同时处理(处理贷款转出批量回购及贷款转出月还)
	 * 读取事务控制表数据,若当前交易流水的整个事务未执行，则执行整个事务，若执行过事务，并且其中单个事务失败，则重新执行单个事务，保证失败事务在界面点击时可重复执行
     * @throws Exception 
     * @Title doLoanTransferRedeem
     * @Description TODO
     * @return 
     * @author yanjingying
     * @date 2015-12-17-下午11:47:00
     * @update
     * @throws
	 * */
	public Map<String, String> doLoanTransferRedeemDeal(TCMmCooperorgDealDTO cooperorgDealDTO, String dealCode) throws Exception{
		String returnMsg = "";   //返回信息
		Map<String, String> resultMapA = new HashMap<String, String>();
		Map<String, String> resultMapB = new HashMap<String, String>();
		
		//读取事务控制表数据,若当前交易流水的整个事务未执行，则执行整个事务，若执行过事务，并且其中单个事务失败，则重新执行单个事务，保证失败事务可重复执行
     	Map<String, Object> hashMap = new HashMap<String, Object>();
     	TCMmTransExceptionDTO transExceptionDTO = new TCMmTransExceptionDTO();
		transExceptionDTO.setTransEnName(CimsConstant.COOPERORG_TRANS_EN_NAME_T001);    //事务名称：贷款回购交易发送核心整体事务
		transExceptionDTO.setDealCode(dealCode);   //交易流水号
		hashMap.put("dto", transExceptionDTO);
     	List<TCMmTransExceptionDTO> transExceptionDTOList = tCMmTransExceptionService.searchTCMmTransException(hashMap);
     	
     	/**第一次调用
     	 * 若A成功，则调用B，此时异常表中有A-0000, B-0000或0001或9998;
     	 * 若A失败，不调用B，此时异常表中有A-0001*/
     	
     	if(CollectionsUtils.isEmpty(transExceptionDTOList)) {
     		//调用事务A,事务A成功调用事务B
    		resultMapA = loanRedeemService.doLoanTransferRedeemA(cooperorgDealDTO, null);
    		if(CimsConstant.RET_CODE_SUC.equals(resultMapA.get("resultCode"))){
        		resultMapB = loanRedeemService.doLoanTransferRedeemB(cooperorgDealDTO, null);
    		}
     	}
     	
     	 /**第二次调用，A失败的情况下继续调用A，直至A成功，方可调B*/
     	else if(transExceptionDTOList.size() == 1){
     		String frontNo = null;
     		if(transExceptionDTOList.get(0).getRetCode().equals(CimsConstant.RET_CODE_TIMEOUT)){
     			frontNo = transExceptionDTOList.get(0).getFrontTransNo();
     		} 
    		//调用事务A,事务A成功调用事务B
    		resultMapA = loanRedeemService.doLoanTransferRedeemA(cooperorgDealDTO, frontNo);
    		if(CimsConstant.RET_CODE_SUC.equals(resultMapA.get("resultCode"))){
        		resultMapB = loanRedeemService.doLoanTransferRedeemB(cooperorgDealDTO, null);
    		}
     		
     	}
     	
     	/**第N次调用，但有两条记录后，说明此时A-0000,B-0000或0001或9998*/
     	else if(transExceptionDTOList.size() == 2){
     		for(TCMmTransExceptionDTO dto : transExceptionDTOList){
     			if(CimsConstant.COOPERORG_TRANS_T001_A.equals(dto.getTransNo())){
 					if(CimsConstant.RET_CODE_FAIL.equals(dto.getRetCode())){
     					//失败则重新调用
 						resultMapA = loanRedeemService.doLoanTransferRedeemA(cooperorgDealDTO, null);
     				} else if (CimsConstant.RET_CODE_TIMEOUT.equals(dto.getRetCode())) {
     					//超时
     					resultMapA = loanRedeemService.doLoanTransferRedeemA(cooperorgDealDTO, dto.getFrontTransNo());
     				} else {
     					//成功则直接返回结果
     					resultMapA = new HashMap<String, String>();
     					resultMapA.put("resultCode", dto.getRetCode());
     					resultMapA.put("resultMsg", dto.getRetMsg());
     				}
     			}
     			//事务B失败，直接调用事务B
     			else if(CimsConstant.COOPERORG_TRANS_T001_B.equals(dto.getTransNo())){
     				if(CimsConstant.RET_CODE_FAIL.equals(dto.getRetCode())){
     					//失败则重新调用
     					resultMapB = loanRedeemService.doLoanTransferRedeemB(cooperorgDealDTO, null);
     				} else if (CimsConstant.RET_CODE_TIMEOUT.equals(dto.getRetCode())) {
     					//超时
     					resultMapB = loanRedeemService.doLoanTransferRedeemB(cooperorgDealDTO, dto.getFrontTransNo());
     				} else {
     					//成功\无需调用、则直接返回结果
     					resultMapB = new HashMap<String, String>();
     					resultMapB.put("resultCode", dto.getRetCode());
     					resultMapB.put("resultMsg", dto.getRetMsg());
     				}
     			}
     			//如果A事务未成功的情况，跳出循环不调用B
     			if (!CimsConstant.RET_CODE_SUC.equals(resultMapA.get("resultCode"))) {
     				break;
     			}
     		}
     	}
     	
     	//两个事务必须同时成功，才可更新交易状态
     	String totalRes = "false";
     	//A成功、B成功|无需调用
		if(CimsConstant.RET_CODE_SUC.equals(resultMapA.get("resultCode")) 
				&& (CimsConstant.RET_CODE_SUC.equals(resultMapB.get("resultCode")) 
						|| CimsConstant.RET_CODE_NO_INVOKE.equals(resultMapB.get("resultCode")) )){
			//A成功、B成功/无需调用：更新【合作机构交易流水表】交易状态为03-回购完成
			cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH); //交易状态为03-回购完成
			cooperorgDealDTO.setDealDate(new java.util.Date());  //交易日期
			cooperorgDealDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));        //更新时间
			cooperorgDealService.updateTCMmCooperorgDeal(cooperorgDealDTO);
			totalRes = "true";
		}else if(  
			//A失败 B空
			//A失败 B失败
			//A失败 B无需调用
			//以上情况除外，需改为回购中
			!(CimsConstant.RET_CODE_FAIL.equals(resultMapA.get("resultCode")) && StringUtil.isEmpty(resultMapB.get("resultCode")))
			&& !(CimsConstant.RET_CODE_FAIL.equals(resultMapA.get("resultCode")) && CimsConstant.RET_CODE_FAIL.equals(resultMapB.get("resultCode")))
			&& !(CimsConstant.RET_CODE_FAIL.equals(resultMapA.get("resultCode")) && CimsConstant.RET_CODE_NO_INVOKE.equals(resultMapB.get("resultCode")))
		){
			//A成功、B失败：更新【合作机构交易流水表】交易状态为02-回购中
			cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_WAY); //交易状态为02-回购中
			cooperorgDealDTO.setDealDate(new java.util.Date());  //交易日期
			cooperorgDealDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));        //更新时间
			cooperorgDealService.updateTCMmCooperorgDeal(cooperorgDealDTO);
		}
		//返回前台信息
		returnMsg =  (resultMapA.get("resultMsg") == null ? "" : resultMapA.get("resultMsg")) + "@@"
					+ (resultMapB.get("resultMsg") == null ? "" : resultMapB.get("resultMsg"));
		
		Map<String, String> retMap = new HashMap<String, String>();
		retMap.put("totalRes", totalRes);
		retMap.put("totalMsg", returnMsg);
     	return retMap;
	}
	/**
	 * @throws Exception 
	 * 删除受让赎回流水
	 * @Title deleteDealCode
	 * @Description TODO 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-2-24-下午3:48:55
	 * @update 
	 * @throws
	 */
	public void deleteDealCode(String dealCodes) throws Exception{
		if(SimpleStringUtils.isEmpty(dealCodes)) throw new Exception("删除失败！传入的参数主键为null");
		
		dealCodes = "'"+dealCodes.replace(",", "','")+"'";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dealCodes", dealCodes);
		List<DealDto> dlist = dealDao.getCooperorgDealByDelete(paramMap);
		if(dlist==null||dlist.size()==0){
			
			dealDao.updateTcmmRedeemDetailByDealCodes(paramMap);
			dealDao.deleteDealCode(paramMap);
			dealDao.deleteCreditDealDetailByDealCode(paramMap);
			
		}else{
			StringBuffer resultdealCodes = new StringBuffer();
			for (DealDto dealDto : dlist) {
				resultdealCodes.append(dealDto.getDealCode()).append(",");
			}
			throw new Exception("交易流水已经存在赎回标记的债权不能删除，"+resultdealCodes.deleteCharAt(resultdealCodes.length()-1).toString());
		}
		
	}
	/**
	 * @throws Exception 
	 * 校验受让赎回导入的债权
	 * @Title doImportCheck
	 * @Description TODO
	 * @param creditDetailList
	 * @param dto 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-2-25-下午5:00:33
	 * @update 
	 * @throws
	 */
	public void doImportCheck(List<CreditDetailDto> creditDetailList ,CreditApplyDto dto) throws Exception{
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			if(null==creditDetailDto.getDealMakeCreditorValue()){
				throw new Exception("赎回价格不能为空！");
			}
			
			if(null==creditDetailDto.getDealThisMakeCreditorValue()){
				throw new Exception("赎回债权价值不能为空！");
			}
			
			if(!SimpleStringUtils.hasText(creditDetailDto.getTransferId())){
				throw new Exception("转让编号不能为空！");
			}
			
			if(!SimpleStringUtils.hasText(creditDetailDto.getCreditCode())){
				throw new Exception("债权编号不能为空！");
			}
			
			if(null==creditDetailDto.getRedeemDate()){
				throw new Exception("赎回日期不能为空！");
			}
			if(dto.getRedeemDate().compareTo(creditDetailDto.getRedeemDate())!=0){
				throw new Exception("债权明细的赎回日期必须与交易的赎回日期相同！");
			}
			if(null==creditDetailDto.getDealCreditorStatus()){
				throw new Exception("交互状态不能为空！");
			}

			Date date = new Date();
			boolean flag = DateTimeUtils.dateCompare(creditDetailDto.getRedeemDate(), date);
			if(flag) throw new Exception("赎回日期不能大于今天！");
		}
	}
	
	/**
	 * @throws Exception 
	 * 校验债权转让导入的债权
	 * @Title doImportCheckTbj
	 * @Description TODO
	 * @param creditDetailList
	 * @param dto 
	 * @update 
	 * @throws
	 */
	private void doImportCheckTbj(String busiNoForInteract,List<CreditDetailDto> resultList,List<CreditDetailDto> creditDealList,String dealCode,String creditAffiliation) throws Exception{

		
		List<String> cooperorgPackageNames = new ArrayList<String>();
		for (CreditDetailDto creditDetailDto : resultList) {
			cooperorgPackageNames.add(creditDetailDto.getCooperorgPackageName());
			if(null==creditDetailDto.getCooperorgPackageName()){
				throw new Exception("机构理财包不能为空！");
			}
			if(null==creditDetailDto.getTransferId()){
				throw new Exception("转让编号不能为空！");
			}
			if(null==creditDetailDto.getCreditCode()){
				throw new Exception("债权编号不能为空！");
			}
			if(null==creditDetailDto.getDealCreditorStatus()){
				throw new Exception("交互状态不能为空！");
			}
			if(null==creditDetailDto.getPackageNum()){
				throw new Exception("所属包编号不能为空！");
			}
		}
		
		//验证机构理财包是否重复
		Set<String> s = new HashSet<String>(cooperorgPackageNames);
		if (s.size()!=1) {
			throw new Exception("导入excel里的机构理财包号必须相同!");
		}
		
		CreditDetailDto creditDetailDto = resultList.get(0);
		DealDto dealDto = this.TbjCooperorgDealData(dealCode);
		
		TCMmCreditPackageDTO creditPackageDTO = creditRightService.getCreditPackageForUnique(dealDto.getCooperorgCode(),
				creditDetailDto.getCooperorgPackageName(), dealDto.getContractCode());
		
		Map<String, Object> searchParams = new HashMap<String, Object>();
		CreditDetailDto creditDetailDTO = new CreditDetailDto();
		creditDetailDTO.setCooperorgPackageName(creditDetailDto.getPackageNum());
		creditDetailDTO.setCooperorgCode(dealDto.getCooperorgCode());
		creditDetailDTO.setContractCode(dealDto.getContractCode());
		searchParams.put("dto", creditDetailDTO);
		List<TCMmCreditDetailDTO>  tCMmCreditDetailDTOs = creditDetailDao.searchTCMmCreditDetail(searchParams);
		if(creditDetailDto.getPackageNum().equals(creditDetailDto.getCooperorgPackageName())){
			//债权确认
			this.sureCreditDataInfo(busiNoForInteract, resultList, creditDealList, dealDto.getCooperorgCode(), creditAffiliation, dealCode);
			
		}else if(null != creditPackageDTO && !CollectionsUtils.isEmpty(tCMmCreditDetailDTOs)){
			//债权确认
			this.sureCreditDataInfo(busiNoForInteract, resultList, creditDealList, dealDto.getCooperorgCode(), creditAffiliation, dealCode);
			//铜板街拆包操作
			this.doTbjCooperorgPackageName(resultList,dealCode,false);
			
		}else if(null == creditPackageDTO){
			//债权确认
			this.sureCreditDataInfo(busiNoForInteract, resultList, creditDealList, dealDto.getCooperorgCode(), creditAffiliation, dealCode);
			//铜板街拆包操作
			this.doTbjCooperorgPackageName(resultList,dealCode,true);
			
		}else if(null != creditPackageDTO && CollectionsUtils.isEmpty(tCMmCreditDetailDTOs)){
			throw new Exception("导入excel里的机构理财包号与所属债权包重名！");
		}
		
	}
	
	/**
	 * 
	 * @Title updateTransferCreditCostValue
	 * @Description TODO
	 * @param creditDetailList
	 * @param dto
	 * @throws Exception 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-2-25-下午5:10:17
	 * @update 
	 * @throws
	 */
	public void updateTransferCreditCostValue(List<CreditDetailDto> creditDetailList ,CreditApplyDto dto) throws Exception{
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			if("确认".equals(creditDetailDto.getDealCreditorStatus())){
				
				Map<String, Object> params = new HashMap<String, Object>();
				TCMmCreditDetailDTO thisCreditDetail = new TCMmCreditDetailDTO();
				thisCreditDetail.setTransferId(creditDetailDto.getTransferId());
				params.put("dto", thisCreditDetail);
				List<TCMmCreditDetailDTO> slist = creditDetailDao.searchTCMmCreditDetail(params);
				if(slist!=null&&slist.size()>0)
					{thisCreditDetail = creditDetailDao.searchTCMmCreditDetail(params).get(0);}
				else
					{continue;}
				if(CimsConstant.CREDIT_STATUS_WIN.equals(thisCreditDetail.getCreditorStatus())){
					Map<String, Object> searchParams = new HashMap<String, Object>();
					TCMmCreditDealDetailDTO creditDealDetail = new TCMmCreditDealDetailDTO();
					//2,更新债权交易明细表，保存回复的价格、赎回的状态、赎回日期
					creditDealDetail.setTransferId(creditDetailDto.getTransferId());
					creditDealDetail.setDealStreamCode(dto.getDealCode());
					creditDealDetail.setMakeCreditorValue(creditDetailDto.getDealMakeCreditorValue());//赎回价格
					creditDealDetail.setThisMakeCreditorValue(creditDetailDto.getDealThisMakeCreditorValue());//赎回债权价值
					creditDealDetail.setCreditorStatus(CimsConstant.CREDIT_STATUS_RED);// 赎回状态
					creditDealDetail.setRedeemDate(creditDetailDto.getRedeemDate());// 赎回日期
					searchParams.put("dto", creditDealDetail);
					
					dealDao.updateCreditDealDetailMakeCreditValue(searchParams);
				}
			}else if ("取消".equals(creditDetailDto.getDealCreditorStatus())){
				// 删除交易流水明细
				creditRight.deleteTCMmCreditDealDetailByTransferIds(new BaseDTO(), creditDetailDto.getTransferId(), dto.getDealCode());
				// 修改债权明细赎回标记
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("transferId", creditDetailDto.getTransferId());
				dealDao.updateTcmmRedeemDetailByTransferId(paramMap);
				
			}
		}
		Map<String, Object> dealparamMap = new HashMap<String, Object>();
		dealparamMap.put("dealCode", dto.getDealCode());
		dealDao.updateTcmmRedeemDealSum(dealparamMap);
	}
	
	/**根据流水号更新赎回状态
	 * @update 
	 * @throws
	 */
	public void updateTcmmRedeemDetailByDealCode( DealDto dto,String redemptionStatus) throws Exception{
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("dto", dto);
			searchParams.put("redemptionStatus", redemptionStatus);
			dealDao.updateTcmmRedeemDetailByDealCode(searchParams);
	}
	
	/**
	 * 
	 * @Description 获取标的日期
	 * @param dealCode
	 * @return
	 * @throws Exception   
	 * List<CreditDetailDto>  
	 * @throws
	 * @author zhangmi
	 * @date 2016-7-18
	 */
	public List<CreditDetailDto> getCreditDeliverDateByDealCode(String dealCode){
		try {
			return dealDao.getCreditDeliverDateByDealCode(dealCode);
		} catch (Exception e) {
			logger.error("获取标的日期异常！"+ExceptionUtils.getStackTraceAsString(e));
		}
		return null;
	}
	
	/**
	 * 根据二次购买交易编号-查询月还对应的信息
	 * @Title getSecondMonthCreditDetails
	 * @Description TODO
	 * @param dto
	 * @return 
	 * List<DealDto> 
	 * @author zhangmi
	 * @date 2016-8-5-下午5:01:17
	 * @update 
	 * @throws
	 */
	public List<DealDto> getSecondMonthCreditDetails(Map<String,Object> params){
		return dealDao.getSecondMonthDealListByPaging(params);
	}
	/**
	 * 首页-我的任务（债权受让、债权转让、二次购买、贷款款转出）全部交易类型
	 * @param searchParams
	 * @return
	 * @throws Exception
	 */
	public List<DealDto> searchMyTaskListByPaging(Map<String,Object> searchParams) throws Exception {
		List<DealDto> dataList =  dealDao.searchMyTaskListByPaging(searchParams);
		return dataList;
	}
	/**
	 * 首页-我的任务（债权转让、债权受让、二次购买）
	 * @param searchParams
	 * @return
	 * @throws Exception
	 */
	public List<DealDto> searchMyTaskListDetailByPaging(Map<String,Object> searchParams) throws Exception {
		List<DealDto> dataList =  dealDao.searchMyTaskListDetailByPaging(searchParams);
		return dataList;
	}
	/**
	 * 首页-我的任务（贷款转出）
	 * @param searchParams
	 * @return
	 * @throws Exception
	 */
	public List<DealDto> searchMyTaskListLoanDetailByPaging(Map<String,Object> searchParams) throws Exception {
		List<DealDto> dataList =  dealDao.searchMyTaskListLoanDetailByPaging(searchParams);
		return dataList;
	}
	
	/**
	 * 
	 * @Title doLoanDealSettle
	 * @Description TODO
	 * @param dealDto 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-8-26-下午3:08:58
	 * @update 
	 * @throws
	 */
	public void doLoanDealSettle(DealDto dealDto) throws Exception{
		if(dealDto==null||StringUtils.isBlank(dealDto.getDealCode())){
			throw new Exception("交易流水号不能为空!");
		}
		List<String> param = new ArrayList<String>();
		param.add(dealDto.getDealCode());
		List<DealDto> list = dealDao.getCooperorgDealByDealCodeList(param);
	    if(list==null||list.size()==0){
	    	throw new Exception("没有需要结算的流水号!");
	    }else{
	    	dealDto = list.get(0);
		}
	    if("02".equals(dealDto.getCostState())){
	    	throw new Exception("此交易已经发送过结算申请!");
	    }else if ("03".equals(dealDto.getCostState())){
	    	throw new Exception("此交易已结算完成!");
	    }
	    int resultLoanCount = ldao.getCountLoanDetailForSettle(SearchParamUtil.getSearchParam(dealDto));
	    
	    if(resultLoanCount>0){
	    	throw new Exception("此交易下还有未放款成功的贷款，不允许结算！");
	    }
	    
	    List<LoanSettleApplyIdDto> loanSettleApplyIdlist = ldao.getLoanSettleApplyIdByDealCode(SearchParamUtil.getSearchParam(dealDto));
	    if(CollectionsUtils.isEmpty(loanSettleApplyIdlist)){
	    	throw new Exception("没有可结算的贷款！");
	    }
	    String settleApplyId = this.doBuildSettleApplyId(loanSettleApplyIdlist);
	    if(StringUtils.isEmpty(settleApplyId)){
	    	throw new Exception("结算编号生成失败！");
	    }
		List<LoanDetailDto> loanlist = ldao.getLoanDetailForSettle(SearchParamUtil.getSearchParam(dealDto));
		if(loanlist==null||loanlist.size()==0){
			throw new Exception("没有可结算的贷款!");
		}
		for (LoanDetailDto loanDetailDto : loanlist) {
			if(loanDetailDto.getServiceCharge()==null||loanDetailDto.getCautionMoney()==null){
				throw new Exception(loanDetailDto.getContractNo()+":服务费或保证金为空，不能发送结算申请!");
			}
		}
		LoanDealSettleDto loanDealSettleDto = new LoanDealSettleDto();
		loanDealSettleDto.setApplyId(settleApplyId);
		loanDealSettleDto.setAccountFeesFlag("0");
		loanDealSettleDto.setApplyName(sessionAPI.getCurrentUserInfo().getUserName());
		loanDealSettleDto.setCooperorgCode(dealDto.getCooperorgCode());
		loanDealSettleDto.setCount(loanlist.size());
		loanDealSettleDto.setTotalCashDeposit(dealDto.getCautionMoney());
		loanDealSettleDto.setTotalServiceCharge(dealDto.getServiceCharge());
		loanDealSettleDto.setLoanList(loanlist);
		iCInteract.sendLoanDealSettleApply(loanDealSettleDto);
		
		/**
		 * 修改结算编号，修改状态。
		 */
    	dealDto.setApplyCode(settleApplyId);
    	ldao.updateLoanSettleApplyIdByDealCode(SearchParamUtil.getSearchParam(dealDto));
		dealDao.updateCooperorgDealCostStatus(SearchParamUtil.getSearchParam(dealDto));
	}
	/**
	 * 生成结算编号
	 * @Title doBuildSettleApplyId
	 * @Description TODO 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-8-30-下午4:54:05
	 * @update 
	 * @throws
	 */
	public String doBuildSettleApplyId(List<LoanSettleApplyIdDto> loanSettleApplyIdlist){
		if(CollectionsUtils.isEmpty(loanSettleApplyIdlist)){
			return "";
		} else{
			String settleApplyId = "";
			for (LoanSettleApplyIdDto loanSettleApplyIdDto : loanSettleApplyIdlist) {
				if(StringUtils.isEmpty(loanSettleApplyIdDto.getSettleApplyId())){
					settleApplyId =  loanSettleApplyIdDto.getDealCode() + "_1";
					break;
				}else{
					String settleApplyIds[] =loanSettleApplyIdDto.getSettleApplyId().split("_");
					settleApplyId = settleApplyIds[0]+"_"+(Integer.valueOf(settleApplyIds[1])+1);
					break;
				}
			}
			return settleApplyId;
		}
			
	}
	/**
	 * 调用进件调配完成通知
	 * @Title doSendCooperorgNotice
	 * @Description TODO
	 * @param dto
	 * @return 
	 * String 
	 * @date 2016-11-17-上午10:09:25
	 * @update 
	 * @throws
	 */
	public String doSendCooperorgNotice(DealDto dto){
		try {
			
			//修改交易状态为03
			Map<String, Object> paramMap = new HashMap<String, Object>();
			dto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);
			paramMap.put("dto", dto);
			tCMmCooperorgDealDao.updateTCMmCooperorgDeal(paramMap);
			
			//1、查询额度编号
			Map<String,Object> searchParams = new HashMap<String,Object>();
			searchParams.put("dto", dto);
			List<RequestNoiteFinishDTO> nflist = dealDao.getQuotaCodeInfo(searchParams);
			//2、组装请求dto
			RequestNoiteFinishListDTO content = new RequestNoiteFinishListDTO();
			content.setNoiteList(nflist);
			//3、发送
			jieYueSend.noticeLoanFinish(dto.getCooperorgCode(), content);
			return "发送成功！";
		} catch (Exception e) {
			return "发送失败："+e.getMessage();
		}
	}
	/**
	 * 
	 * @Title doSendCooperorgNoticeByCredit
	 * @Description TODO
	 * @param dto
	 * @return 
	 * String 
	 * @author lizhiqiang
	 * @date 2016-12-27-下午3:13:27
	 * @update 
	 * @throws
	 */
	public String doSendCooperorgNoticeByCredit(DealDto dto) throws Exception{
		try {
			//修改交易状态为03
			Map<String, Object> paramMap = new HashMap<String, Object>();
			dto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);
			paramMap.put("dto", dto);
			dealDao.updateDealStatus(paramMap);
			//1、查询额度编号
			Map<String,Object> searchParams = new HashMap<String,Object>();
			searchParams.put("dto", dto);
			List<RequestNoiteFinishDTO> nflist = dealDao.getQuotaCodeInfoByCredit(searchParams);
			//2、组装请求dto
			RequestNoiteFinishListDTO content = new RequestNoiteFinishListDTO();
			content.setNoiteList(nflist);
			//3、发送
			jieYueSend.noticeCreditFinish(dto.getCooperorgCode(), content);
			return "发送成功！";
		} catch (Exception e) {
			return "发送失败："+e.getMessage();
		}
	}
	/**
	 * @throws Exception 
	 * 
	 * @Title doconfirmCreditDeal
	 * @Description TODO
	 * @param dto
	 * @return 
	 * String 
	 * @author lizhiqiang
	 * @date 2016-12-28-下午2:39:10
	 * @update 
	 * @throws
	 */
	public void doconfirmCreditDeal(DealDto dto) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		dto.setDealStatusStr("'02','03'");
		paramMap.put("dto", dto);
		List<CreditDetailDto> resultList = dealDao.getDealDetailForCreditInfo(paramMap);
		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		//更新本地流水明细
		this.doExcelImport(resultList);
		//调用核心接口 释放或者确认
		this.updateCreditDealDetailResult(resultList, busiNoForInteract, dto.getCooperorgCode(), dto.getCreditAffiliation(), dto.getDealCode());
		
	}
	/**
	 * 发送赎回完成通知
	 * @Title doSendLoanRedemption
	 * @Description TODO
	 * @param dto
	 * @throws Exception 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-12-29-下午3:00:20
	 * @update 
	 * @throws
	 */
	public void doSendLoanRedemption(DealDto dto) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);
		List<CreditDetailDto> resultList = dealDao.getDealDetailForLoanInfo(paramMap);
		RequestLoanRedemptionReceiveDTO content = new RequestLoanRedemptionReceiveDTO();
		List<RequestLoanRedemptionReceiveLoanDTO> loanList = new ArrayList<RequestLoanRedemptionReceiveLoanDTO>();
		for (CreditDetailDto creditDetailDto : resultList) {
			RequestLoanRedemptionReceiveLoanDTO requestLoanRedemptionReceiveLoanDTO = new RequestLoanRedemptionReceiveLoanDTO();
			requestLoanRedemptionReceiveLoanDTO.setLoanNumber(creditDetailDto.getTransferId());
			requestLoanRedemptionReceiveLoanDTO.setRedeemStatus("01");//赎回成功
			loanList.add(requestLoanRedemptionReceiveLoanDTO);
		}
		content.setLoanList(loanList);
		jieYueSend.noticeLoanRedemption(dto.getCooperorgCode(), content);
		
	}
}